<template>
  <el-config-provider :locale="zhCn">
    <div class="weChatContent">
      <!-- 全局加载蒙版 -->
      <div v-if="isPageLoading || isGroupCreating" class="page-loading-mask">
        <div class="loading-content">
          <div class="loading-spinner">
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
          </div>
          <div class="loading-text">
            <template v-if="isPageLoading">正在加载微信数据...</template>
            <template v-else>正在创建群聊...</template>
          </div>
        </div>
      </div>

      <div v-if="isMessageLoading" class="page-loading-mask">
        <div class="loading-content">
          <div class="loading-spinner">
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
          </div>
          <div class="loading-text">正在加载消息数据...</div>
        </div>
      </div>

      <div class="account" v-if="personalList.length > 0">
        <div class="account-header">
          <span style="color: #44cb84; font-weight: 700; font-size: 18px">{{ onlinePersonCount }}</span
          >/{{ totalPersonCount }}
        </div>
        <div class="account-content">
          <div class="account-content-box" v-for="item in personalList" :key="item.nick_name">
            <img :src="item.avatar_url" alt="" />
            <div>{{ item.nick_name }}</div>
            <el-button type="danger" class="logout-btn" @click.stop="handleLogout(item)">
              <el-icon size="30"> <Close /></el-icon>
            </el-button>
          </div>
        </div>
        <el-icon class="add-account-btn" @click="addNewAcount" style="cursor: pointer" size="30"><Plus /></el-icon>
      </div>
      <template v-if="personalList.length > 0">
        <div class="messageList">
          <div class="messageList-header">
            <div class="search-container">
              <el-input
                v-model="searchInput"
                :placeholder="getSearchPlaceholder()"
                class="search-input"
                clearable
                @input="debouncedSearch"
                @clear="handleClearSearch"
                @keyup.enter="handleSearch"
              />
            </div>
          </div>
          <div class="messageList-icon">
            <div v-for="(icon, type) in iconList" :key="type" class="icon-item" :class="{ active: messageListType === type }" @click="handleClick(type)">
              <div class="icon-wrapper" v-if="type === 'message'">
                <img :src="messageListType === type ? icon.active : icon.default" :alt="type" />
                <el-badge v-if="unreadCount" :value="unreadCount" class="icon-badge" />
              </div>
              <div class="icon-wrapper" v-else-if="type === 'adduser'">
                <img :src="messageListType === type ? icon.active : icon.default" :alt="type" />
                <el-badge
                  v-if="adduserSections && adduserSections[0] && adduserSections[0].value.filter((item) => item.type === 1).length > 0"
                  :value="adduserSections[0].value.filter((item) => item.type === 1).length"
                  class="icon-badge"
                />
              </div>
              <template v-else>
                <img :src="messageListType === type ? icon.active : icon.default" :alt="type" />
              </template>
              <span class="icon-label">{{ iconLabels[type] }}</span>
            </div>
          </div>
          <!-- <div class="message-actions-buttons" v-if="messageListType == 'message'">
          <el-button class="action-btn read-all-btn">
            <el-icon><Check /></el-icon>
            &nbsp; 一键已读
          </el-button>
          <el-button class="action-btn unread-btn">
            <el-icon><Message /></el-icon>
            &nbsp; 展示未读
          </el-button>
        </div> -->
          <div v-if="messageListType == 'message'" class="contacts">
            <!-- 搜索无结果提示 -->
            <div v-if="searchInput && filteredConversations.length === 0" class="empty-search-result">
              <el-empty description="未找到相关消息" :image-size="60">
                <template #image>
                  <el-icon :size="60"><Search /></el-icon>
                </template>
              </el-empty>
            </div>
            <div v-for="(item, index) in searchInput ? filteredConversations : conversations" :key="index" class="section">
              <div class="section-header" @click="toggleSection(index)">
                <div class="section-icon">
                  <el-icon v-if="item.expanded"><ArrowDownBold /></el-icon>
                  <el-icon v-else><ArrowUpBold /></el-icon>
                </div>
                <div class="section-title">{{ item.groupName }}</div>
                <div class="section-count">{{ item.data.length }}</div>
              </div>
              <div v-if="item.expanded">
                <div
                  v-for="element in item.data"
                  :key="element.id"
                  :class="['contact-item', element.isShow ? 'contact-activeItem' : '']"
                  @click="handleClickMessage(element, index)"
                >
                  <!-- 头像 -->
                  <el-badge :value="element.unread" class="avatar-itemTips">
                    <div class="avatar-container" style="margin-right: 0px">
                      <template v-if="element.group_id">
                        <div class="group-avatar" :class="'avatar-count-' + Math.min(element.groupUrlList.length, 9)">
                          <div v-for="(url, index) in element.groupUrlList" :key="index" class="group-avatar-item">
                            <img :src="url" :alt="'群成员' + (index + 1)" />
                          </div>
                        </div>
                      </template>
                      <img v-else :src="element.receiverUrl" :alt="element.receiverName" class="avatar" />
                    </div>
                  </el-badge>

                  <!-- 联系人信息 -->
                  <div class="contact-info">
                    <div class="contact-header">
                      <div class="contact-name">{{ element.receiverName }}</div>
                      <div v-if="element.last_message_time" class="contact-time">
                        {{ element.last_message_time }}
                      </div>
                    </div>
                    <div class="contact-status">
                      {{ element.last_message }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="messageListType == 'users'" class="contacts">
            <!-- 搜索无结果提示 -->
            <div v-if="searchInput && filteredUsersSections.length === 0" class="empty-search-result">
              <el-empty description="未找到相关联系人" :image-size="60">
                <template #image>
                  <el-icon :size="60"><Search /></el-icon>
                </template>
              </el-empty>
            </div>
            <div class="section-headerBtn" v-if="(searchInput ? filteredUsersSections : usersSections).some((section) => section.value.length > 0)">
              <el-button v-if="!isCreatGroup" class="create-group-btn" type="primary" @click="isCreatGroup = true">创建群聊</el-button>
              <div v-if="isCreatGroup" class="group-action-buttons">
                <el-button class="confirm-btn" type="success" @click="creatGroup">确认</el-button>
                <el-button class="cancel-btn" type="danger" @click="cancelCreateGroup">取消</el-button>
              </div>
            </div>
            <div v-for="item in searchInput ? filteredUsersSections : usersSections" :key="item.key" class="section">
              <div class="section-header">
                <div class="section-title">{{ item.key }}</div>
              </div>
              <div v-for="element in item.value" :key="element.wx_id" class="contact-item" @click="handleClickUserContent(element)">
                <!-- 头像 -->
                <div class="avatar-container">
                  <img :src="element.avatar_url" :alt="element.nick_name" class="avatar" />
                </div>

                <!-- 联系人信息 -->
                <div class="contact-info">
                  <div class="contact-header">
                    <div class="contact-name">{{ element.nick_name }}</div>
                    <el-checkbox v-if="isCreatGroup" v-model="element.checked"></el-checkbox>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="messageListType == 'group'" class="contacts">
            <!-- 搜索无结果提示 -->
            <div v-if="searchInput && filteredGroupSections.length === 0" class="empty-search-result">
              <el-empty description="未找到相关群聊" :image-size="60">
                <template #image>
                  <el-icon :size="60"><Search /></el-icon>
                </template>
              </el-empty>
            </div>
            <div v-for="item in searchInput ? filteredGroupSections : groupSections" :key="item.id" class="section">
              <div class="section-header">
                <div class="section-title">{{ item.key }}</div>
              </div>
              <div v-for="element in item.value" :key="element.wx_id" class="contact-item" @click="handleClickGroupContent(element)">
                <!-- 头像 -->
                <el-badge :value="element.unread" class="avatar-itemTips">
                  <div class="avatar-container" style="margin-right: 0px">
                    <template v-if="element.groupUrlList.length > 0">
                      <div class="group-avatar" :class="'avatar-count-' + Math.min(element.groupUrlList.length, 9)">
                        <div v-for="(url, index) in element.groupUrlList" :key="index" class="group-avatar-item">
                          <img :src="url" :alt="'群成员' + (index + 1)" />
                        </div>
                      </div>
                    </template>
                    <img v-else :src="element.receiverUrl" :alt="element.receiverName" class="avatar" />
                  </div>
                </el-badge>
                <!-- 联系人信息 -->
                <div class="contact-info">
                  <div class="contact-header">
                    <div class="contact-name">{{ element.nick_name }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="messageListType == 'adduser'" class="contacts">
            <!-- 搜索无结果提示 -->
            <div v-if="searchInput && filteredAdduserSections.length === 0" class="empty-search-result">
              <el-empty description="未找到相关好友请求" :image-size="60">
                <template #image>
                  <el-icon :size="60"><Search /></el-icon>
                </template>
              </el-empty>
            </div>
            <div v-for="section in searchInput ? filteredAdduserSections : adduserSections" :key="section.id" class="section">
              <div class="section-header">
                <span class="section-title">{{ section.key }}</span>
                <!-- <span class="section-count" v-if="section.value.length > 0">({{ section.value.length }})</span> -->
                <el-button type="primary" link class="add-friend-btn" @click="showAddFriendDialog = true">
                  <el-icon><Plus /></el-icon>
                  添加好友
                </el-button>
              </div>

              <div v-if="section.value.length > 0" class="section-content">
                <div v-for="element in section.value" :key="element.id" class="contact-item">
                  <!-- 头像 -->
                  <el-avatar :size="48" :src="element.url" :alt="element.fromnickname" class="contact-avatar">
                    <img :src="avatar" />
                  </el-avatar>

                  <!-- 联系人信息 -->
                  <div class="contact-info">
                    <div class="contact-header">
                      <div class="contact-name">{{ element.fromnickname }}</div>
                      <div class="contact-time" v-if="element.create_time">
                        {{ formatTime(element.create_time) }}
                      </div>
                    </div>
                    <div class="contact-status">
                      {{ element.content || '请求添加您为好友' }}
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="contact-actions">
                    <el-button
                      :type="element.status === 1 ? 'primary' : 'success'"
                      :disabled="element.status !== 1"
                      size="small"
                      @click="handleAcceptFriend(element)"
                    >
                      {{ element.status === 1 ? '接受' : '已通过' }}
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 空状态展示 -->
              <div v-else class="empty-state">
                <el-empty description="暂无好友请求" :image-size="60">
                  <template #image>
                    <el-icon :size="60"><User /></el-icon>
                  </template>
                </el-empty>
              </div>
            </div>
          </div>
        </div>
        <div class="messageContent" v-if="(messageContent.wx_id || messageContent.group_id) && messageListType === 'message'">
          <div class="messageContent-header">
            <div class="messageContent-header-name">
              {{ messageContent.remark ? messageContent.remark : messageContent.nick_name }}
            </div>
          </div>
          <div ref="scrollbarRef" style="height: calc(100vh - 50px - 250px); overflow-y: auto" @scroll="handleScroll">
            <!-- 加载更多消息指示器 -->
            <div v-if="isLoading && hasMore" class="loading-more">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>正在加载历史消息...</span>
            </div>
            <!-- 加载失败重试 -->
            <div v-else-if="loadError && hasMore" class="load-error">
              <span>加载失败</span>
              <el-button type="text" size="small" @click="retryLoadMessages">点击重试</el-button>
            </div>
            <!-- 没有更多消息提示 - 只在用户尝试加载更多后显示 -->
            <div v-else-if="!hasMore && hasTriedLoadMore && messageBody.length > 0" class="no-more-messages">
              <span>已显示全部消息</span>
            </div>
            <div class="messageContent-body" v-for="(item, index) in messageBody" :key="item.id">
              <!-- {{ index }} -->
              <div class="messageContent-body-time" v-if="item.message_create_time_str">
                {{ item.message_create_time_str }}
              </div>
              <div class="messageContent-body-msgleft" v-if="item.direction == 'left'">
                <div class="messageContent-body-msgleft-avatar">
                  <img :src="item.senderUrl" alt="" />
                </div>
                <div class="messageContent-body-msgleft-textcontet">
                  <div v-if="item.app_id == 'GROUP'" style="color: #b2b2b2; font-size: 13px; transform: translateY(-5px)">{{ item.senderName }}</div>
                  <div class="messageContent-body-msgleft-textcontet-textbox">
                    <div
                      class="messageContent-body-msgleft-textcontet-textbox-text"
                      v-if="item.message_type == 1"
                      v-html="formatMessageContent(item.message_content)"
                    ></div>
                    <el-checkbox v-if="item.isShowCheck" class="message-checkbox" label="" value="" />
                  </div>
                  <div class="messageContent-body-msgleft-img" v-if="item.message_type == 2">
                    <el-image
                      class="messageContent-body-msgleft-img-imgs"
                      :preview-src-list="[imageUrlfirst + item.message_content]"
                      :src="imageUrlfirst + item.message_content"
                    />
                  </div>
                  <!-- 新增：视频消息展示 -->
                  <div class="messageContent-body-msgleft-video" v-if="item.message_type == 4">
                    <video :src="imageUrlfirst + item.message_content" controls style="max-width: 200px; max-height: 200px"></video>
                  </div>
                  <!-- 新增：语音消息展示 -->
                  <div class="messageContent-body-msgleft-audio" v-if="item.message_type == 3">
                    <div class="audio-container left">
                      <audio :src="imageUrlfirst + item.message_content" controls></audio>

                      <el-tooltip :content="item.transcribedText ? '收起文字' : '转文字'" placement="top">
                        <el-button type="primary" size="small" class="transcribe-btn" :loading="item.transcribing" @click="handleTranscribeAudio(item)">
                          <el-icon><Switch /></el-icon>
                        </el-button>
                      </el-tooltip>
                    </div>
                    <div v-if="item.transcribedText" class="transcribed-text">
                      <div class="transcribed-label">转文字结果：</div>
                      <div class="transcribed-content">{{ item.transcribedText }}</div>
                    </div>
                  </div>
                  <!-- 新增：文件消息展示 -->
                  <div class="messageContent-body-msgleft-file" v-if="item.message_type == 5">
                    <div class="file-container left" @click="handleDownloadFile(item)">
                      <div class="file-icon">
                        <el-icon size="24"><Document /></el-icon>
                      </div>
                      <div class="file-info">
                        <div class="file-name">{{ item.media_file_id || '未知文件' }}</div>
                        <!-- <div class="file-extension">{{ item.file_last_name || '' }}</div> -->
                      </div>
                      <div class="download-icon">
                        <el-icon size="16"><Download /></el-icon>
                      </div>
                    </div>
                  </div>
                  <div class="messageContent-body-msgleft-textcontet-aiMessage" @click="handleAiMessageClick(item.aiMessage)" v-if="item.isLoading">
                    AI推荐：
                    <Typewriter :text="item.aiMessage" />
                  </div>
                  <div class="messageContent-body-msgleft-textcontet-aiMessage" @click="handleAiMessageClick(item.ai_message)" v-if="item.ai_message">
                    AI推荐：
                    {{ item.ai_message }}
                  </div>
                  <!-- <div class="message-actions">
                  <div class="action-item" @click="copyMessage(item.message_content)">
                    <el-icon><Document /></el-icon>
                    <span>复制</span>
                  </div>
                  <div class="action-item" @click="forwardMessage(item)">
                    <el-icon><Share /></el-icon>
                    <span>转发</span>
                  </div>
                  <div class="action-item" @click="quoteMessage(item)">
                    <el-icon><ChatDotRound /></el-icon>
                    <span>引用</span>
                  </div>
                </div> -->
                </div>
              </div>
              <div class="messageContent-body-msgright" v-if="item.direction == 'right'">
                <div class="messageContent-body-msgright-avatar">
                  <img :src="item.senderUrl" alt="" />
                </div>
                <div class="messageContent-body-msgright-textcontet">
                  <div class="messageContent-body-msgright-textcontet-textbox">
                    <el-checkbox v-if="item.isShowCheck" class="message-checkbox" label="" value="" />
                    <div
                      class="messageContent-body-msgright-textcontet-textbox-text"
                      v-html="formatMessageContent(item.message_content)"
                      v-if="item.message_type == 1"
                    ></div>
                  </div>
                  <div class="messageContent-body-msgright-img" v-if="item.message_type == 2">
                    <el-image
                      class="messageContent-body-msgright-img-imgs"
                      :preview-src-list="[imageUrlfirst + item.message_content]"
                      :src="imageUrlfirst + item.message_content"
                    />
                  </div>
                  <!-- 新增：视频消息展示 -->
                  <div class="messageContent-body-msgright-video" v-if="item.message_type == 4">
                    <video :src="imageUrlfirst + item.message_content" controls style="max-width: 200px; max-height: 200px"></video>
                  </div>
                  <!-- 新增：语音消息展示 -->
                  <div class="messageContent-body-msgright-audio" v-if="item.message_type == 3">
                    <div class="audio-container right">
                      <audio :src="imageUrlfirst + item.message_content" controls></audio>
                      <el-tooltip :content="item.transcribedText ? '收起文字' : '转文字'" placement="top">
                        <el-button type="primary" size="small" class="transcribe-btn" :loading="item.transcribing" @click="handleTranscribeAudio(item)">
                          <el-icon><Switch /></el-icon>
                        </el-button>
                      </el-tooltip>
                    </div>
                    <div v-if="item.transcribedText" class="transcribed-text">
                      <div class="transcribed-label">转文字结果：</div>
                      <div class="transcribed-content">{{ item.transcribedText }}</div>
                    </div>
                  </div>
                  <!-- 新增：文件消息展示 -->
                  <div class="messageContent-body-msgright-file" v-if="item.message_type == 5">
                    <div class="file-container right" @click="handleDownloadFile(item)">
                      <div class="download-icon">
                        <el-icon size="16"><Download /></el-icon>
                      </div>
                      <div class="file-info">
                        <div class="file-name">{{ item.media_file_id || '未知文件' }}</div>
                        <!-- <div class="file-extension">{{ item.file_last_name || '' }}</div> -->
                      </div>
                      <div class="file-icon">
                        <el-icon size="24"><Document /></el-icon>
                      </div>
                    </div>
                  </div>
                  <!-- <div class="message-actions">
                  <div class="action-item" @click="copyMessage(item.message_content)">
                    <el-icon><Document /></el-icon>
                    <span>复制</span>
                  </div>
                  <div class="action-item" @click="forwardMessage(item)">
                    <el-icon><Share /></el-icon>
                    <span>转发</span>
                  </div>
                  <div class="action-item" @click="forwardMessage(item)">
                    <el-icon><RefreshLeft /></el-icon>
                    <span>撤回</span>
                  </div>
                  <div class="action-item" @click="quoteMessage(item)">
                    <el-icon><ChatDotRound /></el-icon>
                    <span>引用</span>
                  </div>
                </div> -->
                </div>
              </div>
            </div>
          </div>

          <!-- 已@的成员显示 - 放在输入框容器上面，只在群聊中显示 -->
          <div v-if="selectedAtMembers.length > 0 && messageContent.group_id" class="selected-at-members">
            <div class="at-members-header">已@的成员：</div>
            <div class="at-members-list">
              <el-tag
                v-for="member in selectedAtMembers"
                :key="member.user_id"
                type="primary"
                size="small"
                closable
                @close="removeAtMember(member)"
                class="at-member-tag"
              >
                @{{ member.user_name }}
              </el-tag>
            </div>
          </div>

          <div class="messageContent-bodyinput">
            <div class="messageContent-bodyinput-icon">
              <img @click="toggleEmojiPicker" src="@/assets/icon.png" alt="" ref="emojiIconRef" style="position: relative; z-index: 10" />
              <img @click="handleClickFile" src="@/assets/file.png" alt="" />
              <!-- <img src="@/assets/history.png" alt="" /> -->
              <!-- <img src="@/assets/qr.png" alt="" /> -->
              <!-- <img src="@/assets/work-card.png" alt="" /> -->
              <!-- <el-button class="check-more-btn" @click="checkMore" :type="isShowCheck ? 'danger' : 'primary'">
              {{ isShowCheck ? '取消' : '多选' }}
            </el-button> -->
              <input style="display: none" type="file" ref="fileInput" @change="handleFileChange" :value="fileInputValue" />
              <div class="messageContent-bodyinput-icon-select" v-if="!messageContent.group_id">
                <el-select v-model="radioChange" placeholder="选择回复类型" @change="saveAitype" class="ai-reply-select">
                  <el-option label="人工" value="1" />
                  <el-option label="AI辅助" value="2" />
                  <el-option label="AI接管" value="3" />
                </el-select>
                <!-- AI接管模式加载动画 -->
                <div v-if="radioChange === '3' && isAiProcessing" class="ai-processing-indicator">
                  <div class="ai-loading-spinner">
                    <div class="spinner-dot"></div>
                    <div class="spinner-dot"></div>
                    <div class="spinner-dot"></div>
                  </div>
                  <span class="ai-processing-text">AI正在努力思考中...</span>
                </div>
              </div>
            </div>

            <el-input
              v-model="senMessageContent"
              @keyup.enter="sendMessage(senMessageContent)"
              @input="handleInputChange"
              :rows="7"
              type="textarea"
              :placeholder="messageContent.group_id ? '输入消息内容，输入@可以选择群成员' : '输入消息内容'"
              maxlength="2000"
              show-word-limit
            />

            <!-- @群成员选择器 -->
            <div v-if="showAtMemberSelector && messageContent.group_id" class="at-member-selector">
              <div class="at-member-header">选择要@的群成员</div>
              <div class="at-member-list">
                <div v-for="member in filteredGroupMembers" :key="member.user_id" class="at-member-item" @click="selectAtMember(member)">
                  <img :src="member.user_url" :alt="member.user_name" class="at-member-avatar" />
                  <span class="at-member-name">{{ member.user_name }}</span>
                </div>
              </div>
              <div v-if="filteredGroupMembers.length === 0" class="at-member-empty">没有找到匹配的群成员</div>
            </div>

            <div v-if="showEmojiPicker" ref="emojiPickerRef" :style="emojiPickerStyle">
              <EmojiPicker :i18n="zhConfig" locale="zh" @select="onSelectEmoji" />
            </div>
            <div class="messageContent-bodyinput-btn">
              <el-button @click="clearMessageInput">清空 </el-button>
              <el-button type="primary" @click="sendMessage(senMessageContent)">发送</el-button>
            </div>
          </div>
        </div>
        <div class="mySelfData" v-if="(messageContent.wx_id || messageContent.group_id) && messageListType === 'message'">
          <div class="custom-style">
            <el-segmented v-model="optionsvalue" :options="messageContent.group_id ? ['群聊信息', '聊天记录'] : options" />
          </div>
          <div class="mySelfData-myself" v-if="optionsvalue == '客户档案' && !messageContent.group_id">
            <!-- 客户档案内容 -->
            <div class="mySelfData-myself-header">
              <template v-if="messageContent.group_id && messageContent.groupMembers && messageContent.groupMembers.length">
                <div class="group-avatar" :class="'avatar-count-' + Math.min(messageContent.groupMembers.length, 9)" style="display: flex; align-items: center">
                  <div v-for="member in messageContent.groupMembers.slice(0, 4)" :key="member.user_id" class="group-avatar-item" style="margin-left: -8px">
                    <img
                      :src="member.user_url"
                      :alt="member.user_name"
                      style="width: 36px; height: 36px; border-radius: 50%; border: 2px solid #fff; object-fit: cover"
                    />
                  </div>
                </div>
              </template>
              <template v-else>
                <img :src="messageContent.avatar_url" class="mySelfData-myself-header-avatar" />
              </template>
              <div class="mySelfData-myself-header-content">
                <div class="mySelfData-myself-header-content-name">
                  {{ messageContent.nick_name }}
                  <el-button type="primary" size="small" link @click="showEditFriendNameDialog">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </div>
                <div>微信号：{{ messageContent.wx_account }}</div>
              </div>
            </div>

            <!-- 客户基本信息 -->
            <div class="mySelfData-myself-center">
              <div class="section-header">
                <div class="section-title" @click="toggleBasicInfo" style="cursor: pointer; display: flex; align-items: center">
                  <span>基本信息</span>
                  <el-icon style="margin-left: 8px; transition: transform 0.3s" :style="{ transform: isBasicInfoExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }">
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-button type="primary" link size="small" @click="handleEditCustomer">
                  <el-icon><Edit /></el-icon>
                  编辑信息
                </el-button>
              </div>
              <div v-show="isBasicInfoExpanded" class="info-grid">
                <div class="info-item">
                  <span class="info-label">年龄</span>
                  <span class="info-value">{{ messageContent.age || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">性别</span>
                  <span class="info-value">{{ getGenderText(messageContent.gender) }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">生日</span>
                  <span class="info-value">{{ messageContent.birthday || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">电话</span>
                  <span class="info-value">{{ messageContent.phone || '-' }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">QQ</span>
                  <span class="info-value">{{ messageContent.qq || '-' }}</span>
                </div>
                <div class="info-item info-item-full">
                  <span class="info-label">邮箱</span>
                  <span class="info-value">{{ messageContent.email || '-' }}</span>
                </div>
                <div class="info-item info-item-full">
                  <span class="info-label">地址</span>
                  <span class="info-value">{{ messageContent.address || '-' }}</span>
                </div>
                <div class="info-item info-item-full">
                  <span class="info-label">描述</span>
                  <span class="info-value">{{ messageContent.description || '-' }}</span>
                </div>
              </div>
            </div>

            <!-- 客户来源和所属员工 -->
            <!-- <div class="mySelfData-myself-center" style="margin-top: 12px">
            <div class="section-title">其他信息</div>
            <div class="mySelfData-myself-center-item">
              <div class="mySelfData-myself-center-item-left">客户来源</div>
              <div class="mySelfData-myself-center-item-right">{{ messageContent.source || '-' }}</div>
            </div>
            <div class="mySelfData-myself-center-item">
              <div class="mySelfData-myself-center-item-left">所属员工</div>
              <div class="mySelfData-myself-center-item-right">{{ messageContent.employee || '-' }}</div>
            </div>
            <div class="mySelfData-myself-center-item">
              <div class="mySelfData-myself-center-item-left">添加时间</div>
              <div class="mySelfData-myself-center-item-right">{{ messageContent.create_time || '-' }}</div>
            </div>
            <div class="mySelfData-myself-center-item">
              <div class="mySelfData-myself-center-item-left">更新时间</div>
              <div class="mySelfData-myself-center-item-right">{{ messageContent.update_time || '-' }}</div>
            </div>
          </div> -->

            <!-- 客户标签 -->
            <div class="mySelfData-myself-center" style="margin-top: 12px">
              <div class="section-header">
                <div class="section-title" @click="toggleTags" style="cursor: pointer; display: flex; align-items: center">
                  <span>客户标签</span>
                  <el-icon style="margin-left: 8px; transition: transform 0.3s" :style="{ transform: isTagsExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }">
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-button type="primary" link size="small" @click="addTag">
                  <el-icon><Plus /></el-icon>
                  添加标签
                </el-button>
              </div>
              <div v-show="isTagsExpanded" class="tags-container">
                <template v-if="messageContent.tags && messageContent.tags.length > 0">
                  <el-tag v-for="tag in messageContent.tags" :key="tag.id" class="tag-item" effect="plain" size="small" closable @close="deleteTag(tag)">
                    {{ tag.label_name }}
                  </el-tag>
                </template>
                <div v-else class="no-tags">
                  <el-text type="info">未设置标签</el-text>
                </div>
              </div>
            </div>

            <!-- 用药提醒 -->
            <div class="mySelfData-myself-center" style="margin-top: 12px">
              <div class="section-header">
                <div class="section-title" @click="toggleMedicationReminder" style="cursor: pointer; display: flex; align-items: center">
                  <span>用药提醒</span>
                  <el-icon
                    style="margin-left: 8px; transition: transform 0.3s"
                    :style="{ transform: isMedicationReminderExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }"
                  >
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-button type="primary" link size="small" @click="handleMedicationReminder">
                  <el-icon><Edit /></el-icon>
                  设置提醒
                </el-button>
              </div>
              <div v-show="isMedicationReminderExpanded">
                <div v-if="customerMedicationReminder" class="medication-reminder-grid">
                  <div class="info-item">
                    <span class="info-label">产品</span>
                    <span class="info-value">{{ customerMedicationReminder.productName || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">状态</span>
                    <el-tag :type="customerMedicationReminder.status === '0' ? 'success' : 'danger'" size="small">
                      {{ customerMedicationReminder.status === '0' ? '启用' : '停用' }}
                    </el-tag>
                  </div>
                  <div class="info-item">
                    <span class="info-label">每天次数</span>
                    <span class="info-value">{{ customerMedicationReminder.triple || '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">间隔天数</span>
                    <span class="info-value">{{ customerMedicationReminder.day !== undefined ? customerMedicationReminder.day : '-' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">截至日期</span>
                    <span class="info-value">{{
                      customerMedicationReminder.deadline ? dayjs(customerMedicationReminder.deadline).format('YYYY-MM-DD') : '-'
                    }}</span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">通知客服</span>
                    <span class="info-value">{{ customerMedicationReminder.customerServiceStatus === '0' ? '是' : '否' }}</span>
                  </div>
                  <div v-if="customerMedicationReminder.customerService" class="info-item">
                    <span class="info-label">所属客服</span>
                    <span class="info-value">{{ customerMedicationReminder.customerServiceName || '-' }}</span>
                  </div>

                  <div v-if="customerMedicationReminder.message" class="info-item info-item-full">
                    <span class="info-label">消息内容</span>
                    <span class="info-value">{{ customerMedicationReminder.message }}</span>
                  </div>
                </div>
                <div v-else class="no-medication">
                  <el-text type="info">暂无用药提醒设置</el-text>
                </div>
              </div>
            </div>

            <!-- 购买记录 -->
            <div class="mySelfData-myself-center" style="margin-top: 12px">
              <div class="section-header">
                <div class="section-title" @click="togglePurchaseRecord" style="cursor: pointer; display: flex; align-items: center">
                  <span>购买记录</span>
                  <el-icon
                    style="margin-left: 8px; transition: transform 0.3s"
                    :style="{ transform: isPurchaseRecordExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }"
                  >
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-button type="primary" link size="small" @click="handleAddPurchaseRecord">
                  <el-icon><Plus /></el-icon>
                  新增记录
                </el-button>
              </div>
              <div v-show="isPurchaseRecordExpanded" class="purchase-record-list">
                <div v-if="purchaseRecordList.length > 0" class="record-items">
                  <div v-for="(record, index) in purchaseRecordList.slice(0, 3)" :key="record.id || index" class="purchase-record-card">
                    <!-- 卡片头部：店铺名称和操作按钮 -->
                    <div class="record-header">
                      <div class="shop-info">
                        <span class="shop-name">{{ record.shopName || '未知店铺' }}</span>
                        <!-- <span class="order-date">{{ record.orderDate ? dayjs(record.orderDate).format('MM-DD') : '-' }}</span> -->
                      </div>
                      <div class="record-actions">
                        <el-button type="primary" link size="small" @click="handleEditPurchaseRecord(record, index)">
                          <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button type="danger" link size="small" @click="handleDeletePurchaseRecord(record, index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </div>
                    </div>

                    <!-- 商品信息行 -->
                    <div class="product-row">
                      <div class="product-main">
                        <span class="product-name">{{ record.productName || '未知产品' }}</span>
                      </div>
                      <div class="product-right">
                        <span v-if="record.productSpec" class="product-spec">{{ record.productSpec }}</span>
                        <span class="product-quantity">×{{ record.quantity || 1 }}</span>
                      </div>
                    </div>

                    <!-- 详细信息网格 -->
                    <div class="details-grid">
                      <div class="detail-item">
                        <span class="detail-label">订单号</span>
                        <span class="detail-value">{{ record.orderNo || '-' }}</span>
                      </div>
                      <div v-if="record.productCode" class="detail-item">
                        <span class="detail-label">货号</span>
                        <span class="detail-value">{{ record.productCode }}</span>
                      </div>
                    </div>

                    <!-- 收件人信息单独一行 -->
                    <div v-if="record.receiverName" class="receiver-info">
                      <span class="receiver-label">收件人</span>
                      <span class="receiver-name">{{ record.receiverName }}</span>
                      <span v-if="record.receiverPhone" class="receiver-phone">{{ record.receiverPhone }}</span>
                    </div>

                    <!-- 地址和备注（如果有的话） -->
                    <div v-if="record.receiverAddr || record.remark" class="additional-info">
                      <div v-if="record.receiverAddr" class="address-info">
                        <span class="info-label">地址</span>
                        <span class="info-value">{{ record.receiverAddr }}</span>
                      </div>
                      <div v-if="record.remark" class="remark-info">
                        <span class="info-label">备注</span>
                        <span class="info-value">{{ record.remark }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="purchaseRecordTotal > 3" class="more-records">
                    <el-button type="info" link size="small" @click="handleViewAllRecords"> 查看全部 {{ purchaseRecordTotal }} 条记录 </el-button>
                  </div>
                </div>
                <div v-else class="no-records">
                  <el-text type="info">暂无购买记录</el-text>
                </div>
              </div>
            </div>
          </div>

          <!-- 全部动态 -->
          <div class="mySelfData-myself" v-if="optionsvalue == '全部动态' && !messageContent.group_id">
            <div class="mySelfData-myself-center">
              <div class="section-title">
                客户动态
                <div class="activity-actions">
                  <el-button type="success" size="small" @click="showAddActivityDialog" style="margin-left: 10px">
                    <el-icon><Plus /></el-icon>
                    添加动态
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click="refreshCustomerActivities"
                    :loading="refreshingActivities"
                    :disabled="refreshCountdown > 0"
                    style="margin-left: 8px"
                  >
                    <el-icon><Refresh /></el-icon>
                    <span v-if="refreshCountdown > 0" style="margin-left: 4px">{{ refreshCountdown }}s</span>
                  </el-button>
                </div>
              </div>
              <div class="timeline-container">
                <el-timeline v-if="messageContent.activities && messageContent.activities.length > 0">
                  <el-timeline-item
                    v-for="(activity, index) in messageContent.activities"
                    :key="index"
                    :timestamp="activity.time"
                    :type="activity.type"
                    :color="activity.color"
                    :data-type="activity.type"
                  >
                    <div class="timeline-content">
                      <div class="timeline-title">{{ activity.title }}</div>
                      <div class="timeline-desc">{{ activity.description }}</div>
                    </div>
                  </el-timeline-item>
                </el-timeline>

                <!-- 加载更多按钮 -->
                <div v-if="messageContent.activities && messageContent.activities.length > 0" class="load-more-container">
                  <el-button v-if="activitiesPage.hasMore" type="primary" link @click="loadMoreActivities" :loading="activitiesLoading" class="load-more-btn">
                    {{ activitiesLoading ? '加载中...' : '加载更多' }}
                  </el-button>
                  <div v-else-if="activitiesPage.total > activitiesPage.size" class="no-more-data">
                    <span>已加载全部 {{ activitiesPage.total }} 条记录</span>
                  </div>
                </div>

                <!-- 空状态占位 -->
                <div v-else class="empty-activities">
                  <el-empty description="暂无客户动态" :image-size="80">
                    <template #image>
                      <el-icon :size="80" style="color: #c0c4cc"><Document /></el-icon>
                    </template>
                    <template #description>
                      <span style="color: #909399; font-size: 14px">该客户暂无动态记录</span>
                    </template>
                  </el-empty>
                </div>
              </div>
            </div>
          </div>

          <!-- 聊天记录 -->
          <ChatHistory
            v-if="optionsvalue == '聊天记录'"
            ref="chatHistoryRef"
            :msgprofilewx_id="msgprofilewx_id"
            :messageContent="messageContent"
            :nowExprentTag="nowExprentTag"
            :imageUrlfirst="imageUrlfirst"
            @transcribeAudio="handleTranscribeAudio"
            @downloadFile="handleDownloadFile"
            @processMessageList="processMessageList"
            @msgSendMessages="handleChatHistoryMsgSendMessages"
          />
          <!-- 群聊信息 -->
          <div class="mySelfData-myself" v-if="messageContent.group_id && optionsvalue == '群聊信息'">
            <div class="mySelfData-myself-header">
              <!-- <img :src="messageContent.avatar_url" class="mySelfData-myself-header-avatar" /> -->
              <div class="mySelfData-myself-header-content">
                <div class="mySelfData-myself-header-content-name">
                  {{ messageContent.nick_name }}
                  <el-button type="primary" size="small" link @click="showEditGroupNameDialog">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </div>
                <div>群成员总数：{{ messageContent.group_member_count || (messageContent.groupMembers ? messageContent.groupMembers.length : 0) }}</div>
              </div>
              <el-tooltip content="退出群聊" placement="top">
                <el-button type="danger" size="small" link @click="handleExitGroup" :loading="isExitingGroup" class="exit-group-btn">
                  <el-icon><Close /></el-icon>
                </el-button>
              </el-tooltip>
            </div>

            <div class="mySelfData-myself-center">
              <div class="section-header">
                <div class="section-title" @click="toggleGroupMembers" style="cursor: pointer; display: flex; align-items: center">
                  <span>群成员列表</span>
                  <el-icon
                    style="margin-left: 8px; transition: transform 0.3s"
                    :style="{ transform: isGroupMembersExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }"
                  >
                    <ArrowRight />
                  </el-icon>
                </div>
                <span class="member-count"
                  >{{ messageContent.group_member_count || (messageContent.groupMembers ? messageContent.groupMembers.length : 0) }}人</span
                >
              </div>
              <div v-show="isGroupMembersExpanded" class="group-members-container">
                <div class="group-members-grid">
                  <div class="group-member-item" v-for="member in displayedGroupMembers" :key="member.user_id" @click="quickAtMember(member)">
                    <img :src="member.user_url" alt="" class="member-avatar" />
                    <div class="member-name">{{ member.user_name }}</div>
                    <div class="at-member-btn">@</div>
                  </div>
                  <!-- 邀请好友按钮 -->
                  <div class="group-member-item invite-member-item" @click="handleInviteFriends">
                    <div class="invite-member-icon">
                      <el-icon><Plus /></el-icon>
                    </div>
                    <div class="member-name">邀请好友</div>
                  </div>
                </div>
                <div v-if="hasMoreMembers" class="show-more-container">
                  <el-button type="primary" link size="small" @click="toggleShowAllMembers">
                    {{ showAllGroupMembers ? '收起' : `查看更多 (${messageContent.groupMembers.length - 15}人)` }}
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 群聊标签 -->
            <div class="mySelfData-myself-center" style="margin-top: 12px">
              <div class="section-header">
                <div class="section-title" @click="toggleGroupTags" style="cursor: pointer; display: flex; align-items: center">
                  <span>群聊标签</span>
                  <el-icon style="margin-left: 8px; transition: transform 0.3s" :style="{ transform: isGroupTagsExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }">
                    <ArrowRight />
                  </el-icon>
                </div>
                <el-button type="primary" link size="small" @click="addGroupTag">
                  <el-icon><Plus /></el-icon>
                  添加标签
                </el-button>
              </div>
              <div v-show="isGroupTagsExpanded" class="tags-container">
                <template v-if="messageContent.tags && messageContent.tags.length > 0">
                  <el-tag v-for="tag in messageContent.tags" :key="tag.id" class="tag-item" effect="plain" size="small" closable @close="deleteGroupTag(tag)">
                    {{ tag.label_name }}
                  </el-tag>
                </template>
                <div v-else class="no-tags">
                  <el-text type="info">未设置标签</el-text>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <div v-else class="login-tip">
        <div class="login-tip-content">
          <el-icon class="login-icon"><Message /></el-icon>
          <h2>欢迎使用微信管理系统</h2>
          <p>请先登录微信账号以开始使用</p>
          <el-button type="primary" @click="addNewAcount" class="login-btn"> 扫码登录 </el-button>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogAddAccount" title="扫码登录" width="600px">
      <div class="qrcode-container">
        <div class="qrcode-wrapper">
          <div v-if="!qrcodeUrl && !isQrcodeError" class="qrcode-loading">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>正在生成二维码...</span>
          </div>
          <div v-else-if="isQrcodeError" class="qrcode-error">
            <el-icon class="error-icon"><Warning /></el-icon>
            <span>获取二维码失败</span>
            <el-button type="primary" size="small" @click="generateQrcode" class="refresh-btn"> 刷新二维码 </el-button>
          </div>
          <div v-else-if="isQrcodeExpired" class="qrcode-expired">
            <el-icon class="expired-icon"><Clock /></el-icon>
            <span>二维码已过期</span>
            <el-button type="primary" size="small" @click="generateQrcode" class="refresh-btn"> 刷新二维码 </el-button>
          </div>
          <div v-else class="qrcode-content">
            <img :src="qrcodeUrl" alt="登录二维码" class="qrcode-image" />
            <div class="qrcode-tip">请使用微信扫描二维码登录</div>
            <div class="qrcode-countdown" v-if="qrcodeCountdown > 0">
              <span>{{ qrcodeCountdown }}秒后过期</span>
            </div>
          </div>
        </div>
        <div class="qrcode-status" v-if="qrcodeStatus">
          <el-icon :class="qrcodeStatus.icon" :style="{ color: qrcodeStatus.color }">
            <component :is="qrcodeStatus.icon" />
          </el-icon>
          <span>{{ qrcodeStatus.text }}</span>
        </div>
      </div>
    </el-dialog>
    <!-- 添加标签对话框 -->
    <el-dialog v-model="tagDialogVisible" title="新增标签" width="400px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="tag-dialog-content">
        <div class="tag-suggestions">
          <div class="suggestion-header">
            <div class="suggestion-title">已选择 {{ selectedTags.length }} 个标签</div>
          </div>
          <div class="suggestion-tags">
            <el-tag
              v-for="tag in tagOptions"
              :key="tag.id"
              class="suggestion-tag"
              :class="{ 'is-selected': selectedTags.some((t) => t.id === tag.id) }"
              @click="handleTagSelect(tag)"
            >
              {{ tag.label_name }}
              <el-icon v-if="selectedTags.some((t) => t.id === tag.id)" class="check-icon"><Check /></el-icon>
            </el-tag>
          </div>
        </div>
        <div class="tag-input">
          <div style="display: flex; gap: 8px; align-items: center">
            <el-input v-model="newTag" placeholder="请输入自定义标签名称" class="tag-input" clearable>
              <template #prefix>
                <el-icon><PriceTag /></el-icon>
              </template>
            </el-input>
            <el-button type="success" style="height: 32px" @click="handleCustomTag">新增</el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddTag">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改好友备注对话框 -->
    <el-dialog v-model="editFriendNameDialogVisible" title="编辑好友备注" width="400px" destroy-on-close>
      <el-form ref="friendNameFormRef" :model="friendNameForm" :rules="friendNameRules" label-width="80px">
        <el-form-item label="好友备注" prop="name">
          <el-input v-model="friendNameForm.name" placeholder="请输入好友备注（可为空）" maxlength="20" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editFriendNameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditFriendName" :loading="editFriendNameLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改群聊名称对话框 -->
    <el-dialog v-model="editGroupNameDialogVisible" title="编辑群聊名称" width="400px" destroy-on-close>
      <el-form ref="groupNameFormRef" :model="groupNameForm" :rules="groupNameRules" label-width="80px">
        <el-form-item label="群聊名称" prop="name">
          <el-input v-model="groupNameForm.name" placeholder="请输入群聊名称" maxlength="30" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editGroupNameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditGroupName" :loading="editGroupNameLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 购买记录对话框 -->
    <el-dialog v-model="purchaseRecordDialogVisible" title="购买记录" width="800px" destroy-on-close class="purchase-record-dialog">
      <div class="purchase-record-header">
        <el-button type="primary" @click="handleAddPurchaseRecord">
          <el-icon><Plus /></el-icon>
          新增记录
        </el-button>
      </div>

      <el-table :data="purchaseRecordList" v-loading="purchaseRecordLoading" stripe>
        <el-table-column prop="productName" label="产品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="purchaseDate" label="购买日期" width="120" />
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column prop="price" label="价格" width="100" align="right">
          <template #default="{ row }">
            <span>¥{{ row.price || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row, $index }">
            <el-button type="primary" link size="small" @click="handleEditPurchaseRecord(row, $index)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDeletePurchaseRecord(row, $index)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!purchaseRecordList.length && !purchaseRecordLoading" class="empty-state">
        <el-empty description="暂无购买记录" />
      </div>
    </el-dialog>

    <!-- 购买记录编辑对话框 -->
    <el-dialog
      v-model="purchaseRecordFormDialogVisible"
      :title="purchaseRecordFormMode === 'add' ? '新增购买记录' : '编辑购买记录'"
      width="900px"
      destroy-on-close
      class="purchase-record-dialog"
    >
      <el-form ref="purchaseRecordFormRef" :model="purchaseRecordForm" :rules="purchaseRecordFormRules" label-width="120px" class="purchase-record-form">
        <!-- 订单信息 -->
        <div class="form-section">
          <h3 class="section-title">订单信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="店铺名称" prop="shopName">
                <el-input v-model="purchaseRecordForm.shopName" placeholder="请输入店铺名称+平台" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单号" prop="orderNo">
                <el-input v-model="purchaseRecordForm.orderNo" placeholder="请输入订单号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="下单日期" prop="orderDate">
                <el-date-picker v-model="purchaseRecordForm.orderDate" type="date" placeholder="请选择下单日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 收件人信息 -->
        <div class="form-section">
          <h3 class="section-title">收件人信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收件人姓名" prop="receiverName">
                <el-input v-model="purchaseRecordForm.receiverName" placeholder="请输入收件人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收件人手机" prop="receiverPhone">
                <el-input v-model="purchaseRecordForm.receiverPhone" placeholder="请输入收件人手机号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="收件人地址" prop="receiverAddr">
                <el-input v-model="purchaseRecordForm.receiverAddr" placeholder="请输入收件人地址" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品信息 -->
        <div class="form-section">
          <h3 class="section-title">商品信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="purchaseRecordForm.productName" placeholder="请输入产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品货号" prop="productCode">
                <el-input v-model="purchaseRecordForm.productCode" placeholder="请输入产品货号/编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="购买规格" prop="productSpec">
                <el-input v-model="purchaseRecordForm.productSpec" placeholder="请输入购买规格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="购买数量" prop="quantity">
                <el-input-number v-model="purchaseRecordForm.quantity" :min="1" :max="9999" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="purchaseRecordForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息..." maxlength="500" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseRecordFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPurchaseRecordForm" :loading="purchaseRecordFormLoading"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用药提醒设置对话框 -->
    <el-dialog v-model="medicationReminderDialogVisible" title="设置提醒" width="900px" destroy-on-close class="medication-reminder-dialog">
      <el-form
        ref="medicationReminderFormRef"
        :model="medicationReminderForm"
        :rules="medicationReminderFormRules"
        label-width="110px"
        class="medication-reminder-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="medicationReminderForm.productName" placeholder="请输入产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="medicationReminderForm.status">
                  <el-radio value="0">启用</el-radio>
                  <el-radio value="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 提醒设置 -->
        <div class="form-section">
          <h3 class="section-title">提醒设置</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="每天次数" prop="triple">
                <el-input-number v-model="medicationReminderForm.triple" :min="1" placeholder="请输入每天次数" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="间隔天数" prop="day">
                <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
                  <el-radio-group v-model="dayType" @change="handleDayTypeChange">
                    <el-radio value="daily">每天</el-radio>
                    <el-radio value="custom">自定义</el-radio>
                  </el-radio-group>
                  <el-input-number
                    v-if="dayType === 'custom'"
                    v-model="customDayValue"
                    :min="1"
                    placeholder="请输入"
                    style="width: 130px"
                    @change="handleCustomDayChange"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用药截至日期" prop="deadline">
                <el-date-picker v-model="medicationReminderForm.deadline" type="date" placeholder="请选择用药截至日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否通知客服" prop="customerServiceStatus">
                <el-radio-group v-model="medicationReminderForm.customerServiceStatus">
                  <el-radio value="0">是</el-radio>
                  <el-radio value="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 客服设置 -->
        <div class="form-section">
          <h3 class="section-title">客服设置</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="所属客服" prop="customerService">
                <friend-tag-input
                  :selected-friends="selectedCustomerServiceFriends"
                  placeholder="请选择所属客服"
                  @click="customerServiceFriendSelectDialogVisible = true"
                  @remove="handleRemoveCustomerServiceFriend"
                />
                <friend-select-dialog
                  v-model="customerServiceFriendSelectDialogVisible"
                  :multiple="true"
                  :selected-friends="selectedCustomerServiceFriends.map((f) => f.wx_id)"
                  title="选择所属客服"
                  @confirm="handleCustomerServiceFriendSelectConfirm"
                  @cancel="customerServiceFriendSelectDialogVisible = false"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 消息内容 -->
        <div class="form-section">
          <h3 class="section-title">消息内容</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="消息内容" prop="message">
                <el-input v-model="medicationReminderForm.message" type="textarea" :rows="4" placeholder="请输入消息内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="medicationReminderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMedicationReminderForm" :loading="medicationReminderLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑客户信息对话框 -->
    <el-dialog v-model="editCustomerDialogVisible" title="编辑客户信息" width="600px" destroy-on-close class="customer-dialog">
      <el-form ref="editCustomerFormRef" :model="editCustomerForm" :rules="editCustomerFormRules" label-width="80px" class="edit-form">
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="editCustomerForm.age" placeholder="请输入年龄" :max="120" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editCustomerForm.gender">
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="editCustomerForm.birthday" type="date" placeholder="请选择生日" style="width: 100%" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editCustomerForm.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="editCustomerForm.qq" placeholder="请输入QQ号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editCustomerForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editCustomerForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editCustomerForm.description" type="textarea" :rows="3" placeholder="请输入客户描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCustomerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditCustomer" :loading="editCustomerLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加客户动态对话框 -->
    <el-dialog v-model="addActivityDialogVisible" title="新增客户动态" width="500px" destroy-on-close>
      <el-form ref="addActivityFormRef" :model="addActivityForm" :rules="addActivityRules" label-width="80px">
        <el-form-item label="动态内容" prop="remark">
          <el-input v-model="addActivityForm.remark" type="textarea" :rows="4" placeholder="请输入客户动态内容..." maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addActivityDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddActivity" :loading="addActivityLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 邀请好友进群对话框 -->
    <el-dialog v-model="inviteDialogVisible" title="邀请好友进群" width="600px" :close-on-click-modal="false">
      <div class="invite-friends-dialog">
        <div class="dialog-header">
          <p>选择要邀请进入群聊"{{ messageContent.nick_name }}"的好友：</p>
          <el-input v-model="inviteFriendSearchKeyword" placeholder="搜索好友..." clearable class="search-input">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="friends-list">
          <div v-if="filteredInviteFriends.length === 0" class="empty-state">
            <el-empty :description="inviteFriendSearchKeyword ? '未找到匹配的好友' : '暂无好友可邀请'" />
          </div>
          <div v-else>
            <div v-for="section in filteredInviteFriends" :key="section.id" class="friend-section">
              <div class="section-title">{{ section.key }} ({{ section.value.length }})</div>
              <div class="friends-grid">
                <div
                  v-for="friend in section.value"
                  :key="friend.wx_id"
                  class="friend-item"
                  :class="{ selected: selectedFriendsForInvite.some((f) => f.wx_id === friend.wx_id) }"
                  @click="toggleFriendSelection(friend)"
                >
                  <div class="friend-avatar">
                    <img :src="friend.avatar_url" :alt="friend.nick_name" />
                  </div>
                  <div class="friend-name">{{ friend.nick_name }}</div>
                  <div class="friend-checkbox" @click.stop>
                    <el-checkbox :model-value="selectedFriendsForInvite.some((f) => f.wx_id === friend.wx_id)" @change="() => toggleFriendSelection(friend)" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="selected-friends" v-if="selectedFriendsForInvite.length > 0">
          <div class="selected-title">已选择的好友 ({{ selectedFriendsForInvite.length }})：</div>
          <div class="selected-list">
            <el-tag v-for="friend in selectedFriendsForInvite" :key="friend.wx_id" type="primary" closable @close="removeFriendFromSelection(friend)">
              {{ friend.nick_name }}
            </el-tag>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inviteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInviteFriends" :loading="inviteLoading" :disabled="selectedFriendsForInvite.length === 0">
            邀请 ({{ selectedFriendsForInvite.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加好友对话框 -->
    <AddFriendDialog v-model="showAddFriendDialog" :wx-id="personalList.length ? personalList[0].wx_id : ''" @success="onAddFriendSuccess" />
  </el-config-provider>
</template>
<script setup lang="ts">
import { wechatEmojiMap } from '@/utils/wechatEmojiMap';
import Typewriter from './components/Typewriter.vue';
import ChatHistory from './components/ChatHistory.vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import dayjs from 'dayjs';
import {
  msgSend,
  msgprofile,
  msgcontacts,
  getGroupContacts,
  msggroupcreate,
  msgSendMessages,
  msgSendConversations,
  msgGetUser,
  msgSendImage,
  msgSendFile,
  msgupdateAiType,
  msggetAiMessage,
  msgGetQrcode,
  msgGetWxLogin,
  msgGetWxLoginStatus,
  getWxListByaccount,
  msgLogout,
  seleteWechatFriends,
  friendAdd,
  seleteWechatStranger,
  addWechatStranger,
  updateWechatFriends,
  speechToText,
  getCustomerLogList,
  addCustomerLog,
  updateFriendName,
  updateGroupName,
  exitGroup,
  inviteToGroup
} from '@/api/wechat';
import { getAuthenticationList } from '@/api/userRate/friendVerify';
import { ElMessage, ElMessageBox } from 'element-plus';
import { websocket } from '@/utils/socket';
import {
  Search,
  Switch,
  Check,
  Message,
  Plus,
  Close,
  ArrowDown,
  ArrowRight,
  Loading,
  Warning,
  PriceTag,
  Refresh,
  Document,
  Edit,
  User,
  Download,
  Clock
} from '@element-plus/icons-vue';
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch, computed } from 'vue';
import avatar from '@/assets/avatar.jpg';
import message from '@/assets/message.png';
import messageActive from '@/assets/message-hov.png';
import users from '@/assets/users.png';
import usersActive from '@/assets/users-hov.png';
import adduser from '@/assets/adduser.png';
import adduserActive from '@/assets/adduser-hov.png';
import group from '@/assets/group.png';
import groupActive from '@/assets/group-hov.png';
import 'vue3-emoji-picker/css';
import EmojiPicker from 'vue3-emoji-picker';
import AddFriendDialog from '@/components/common/AddFriendDialog.vue';
import { getAllLabel, addLabel } from '@/api/userRate/label';
import FriendTagInput from '@/components/FriendSelect/FriendTagInput.vue';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';

// 在script setup开始处添加类型定义
interface Tag {
  id: string;
  label_name: string;
}

interface MessageContent {
  remark: string;
  nick_name: string;
  wx_account: string;
  avatar_url: string;
  signature: string;
  province: string;
  city: string;
  district: string;
  wx_id: string;
  group_id: string;
  age: string;
  gender: string;
  birthday: string;
  phone: string;
  qq: string;
  email: string;
  address: string;
  description: string;
  source: string;
  employee: string;
  create_time: string;
  update_time: string;
  tags: Tag[];
  activities: Array<{
    time: string;
    type: string;
    color: string;
    title: string;
    description: string;
  }>;
  groupMembers?: Array<{
    user_id: string;
    user_name: string;
    user_url: string;
    join_time: string;
  }>;
  group_member_count?: number;
}

// 页面加载状态
const isPageLoading = ref(true);
const isMessageLoading = ref(false);

const onlinePersonCount = ref(0);
const totalPersonCount = ref(0);
const searchInput = ref('');
const messageListType = ref('message');

// 搜索相关的过滤数据
const filteredConversations = ref<any>([]);
const filteredUsersSections = ref<any>([]);
const filteredGroupSections = ref<any>([]);
const filteredAdduserSections = ref<any>([]);
const messageIcon = ref(message);
const usersIcon = ref(users);
const groupIcon = ref(group);
const adduserIcon = ref(adduser);
const isCreatGroup = ref(false);
const senMessageContent = ref('');
const msgcurrent = ref('1');
const msgsize = ref('50');
const dialogAddAccount = ref(false);
const imageUrlfirst = import.meta.env.VITE_GLOB_APP_IMG_URL;
const personalList: any = ref([]);
const radioChange = ref('3');
const messageContent = ref<MessageContent>({
  remark: '',
  nick_name: '',
  gender: '',
  wx_account: '',
  avatar_url: '',
  signature: '',
  province: '',
  city: '',
  district: '',
  wx_id: '',
  group_id: '',
  age: '',
  birthday: '',
  phone: '',
  qq: '',
  email: '',
  address: '',
  description: '',
  source: '',
  employee: '',
  create_time: '',
  update_time: '',
  tags: [],
  activities: [
    {
      time: '2024-03-20 14:30',
      type: 'success',
      color: '#44cb84',
      title: '新增好友',
      description: '通过群聊"产品交流群"添加为好友'
    },
    {
      time: '2024-03-19 16:45',
      type: 'primary',
      color: '#2b7bef',
      title: '发送消息',
      description: '发送了3条消息，包含产品咨询和价格询问'
    },
    {
      time: '2024-03-18 10:20',
      type: 'warning',
      color: '#e6a23c',
      title: '浏览商品',
      description: '浏览了"高级会员套餐"商品详情页，停留时间5分钟'
    },
    {
      time: '2024-03-17 09:15',
      type: 'danger',
      color: '#f56c6c',
      title: '取消订单',
      description: '取消了订单号：202403170915，原因：价格因素'
    },
    {
      time: '2024-03-16 15:30',
      type: 'success',
      color: '#44cb84',
      title: '完成订单',
      description: '成功购买"基础会员套餐"，订单金额：299元'
    }
  ]
});
const optionsvalue = ref('客户档案');
const options = ['客户档案', '全部动态', '聊天记录'];
// 分组和联系人数据
const conversations: any = ref([]);
const usersSections: any = ref([]);
const adduserSections = ref([
  {
    id: 1,
    key: '新的朋友',
    value: []
  }
]);
const groupSections: any = ref([
  {
    id: 1,
    title: '群聊'
  }
]);
const messageBody: any = ref([]);
const scrollbarRef = ref<any>(null);
const fileInput = ref<any>(null);
const isShowCheck = ref<any>(false);
// AI接管模式处理状态
const isAiProcessing = ref<boolean>(false);
const nowExprentTag = ref('');
const fileInputValue = ref('');
const msgprofilewx_id = ref<string>('');

// 聊天记录组件引用
const chatHistoryRef = ref<InstanceType<typeof ChatHistory> | null>(null);
const currentUsername = JSON.parse(localStorage.getItem('userInfo') || '{}').username;
const isLoading = ref(false);
const hasMore = ref(true);
const loadError = ref(false);
const hasTriedLoadMore = ref(false); // 标记是否已经尝试过加载更多
const shouldAutoScroll = ref(true); // 控制是否应该自动滚动到底部

interface WxProfile {
  wx_id: string;
  nick_name?: string;
  avatar_url?: string;
  isOnline?: boolean;
}

const wxProfile = ref<WxProfile | null>(null);

const getMessageCallback2 = (message: any) => {
  // 1. 基础消息验证
  if (!message) {
    console.warn('收到空消息');
    return;
  }

  // 2. 安全解析消息
  let data: any;
  try {
    data = JSON.parse(message);
  } catch (error) {
    console.error('消息解析失败:', error);
    return;
  }

  // 3. 处理新好友通知
  if (data?.newFriends && personalList.value?.[0]?.wx_id) {
    getPendingFriends(personalList.value[0].wx_id);
  }

  // 4. 保持原有的消息处理逻辑，但添加必要的空值检查
  if (conversations.value) {
    conversations.value.forEach((ele: any) => {
      if (ele?.groupName === nowExprentTag.value) {
        ele.data?.forEach((item: any) => {
          if (item?.isGroup) {
            if (item?.group_id === data?.group_id && item?.isShow) {
              messageBody.value.push(data);
              if (radioChange.value === '2') {
                getAimessage(data);
              }
            }
          } else {
            if (item?.user_id === data?.messageUser && item?.isShow) {
              messageBody.value.push(data);
              if (radioChange.value === '2') {
                getAimessage(data);
              }
            }
          }
        });
      }
    });
  }

  // 5. 安全地更新消息状态
  try {
    getMessgeStation();
  } catch (error) {
    console.error('更新消息状态失败:', error);
  }
};
const getMessageCallback = (message: any) => {
  if (message) {
    let data = JSON.parse(message);

    console.log(data);
    if (radioChange.value == '3' && data.direction == 'right') {
      isAiProcessing.value = false;
    }
    conversations.value.forEach((ele: any) => {
      if (ele.groupName == nowExprentTag.value) {
        ele.data.forEach((item: any) => {
          if (item.isGroup) {
            data.senderName = data.messageName;
            data.app_id == 'GROUP';
            if (item.group_id == data.group_id && item.isShow) {
              messageBody.value.push(data);
            }
          } else {
            if (item.user_id == data.messageUser && item.isShow) {
              messageBody.value.push(data);
              if (radioChange.value == '2' && data.message_type !== '5') {
                getAimessage(data);
              } else if (radioChange.value == '3' && data.direction == 'left' && data.message_type !== '5') {
                // AI接管模式：收到消息后启动加载动画（文件消息除外）
                isAiProcessing.value = true;
              }
            }
          }
        });
      }
    });
    getMessgeStation();
  }
};
// ai辅助功能
const getAimessage = (item: any) => {
  if (item.messageId) {
    messageBody.value.forEach((ele: any) => {
      if (ele.messageId == item.messageId) {
        ele.isLoading = true;
      }
    });
    msggetAiMessage(item.messageId).then((res) => {
      nextTick(() => {
        messageBody.value.forEach((ele: any) => {
          if (ele.messageId == res.data.id) {
            ele.aiMessage = res.data.aiMessage;
            ele.isLoading = true;
          }
        });
      });
    });
  }
};
// 监听 messages 变化，根据标记决定是否自动滚动到底部
watch(
  () => messageBody.value.length,
  () => {
    if (shouldAutoScroll.value) {
      scrollToBottom();
    }
  },
  { deep: true }
);

const initWxProfile = async () => {
  try {
    const storedProfile = localStorage.getItem('msgprofile');
    if (storedProfile) {
      const profile = JSON.parse(storedProfile);
      wxProfile.value = profile;
      msgprofilewx_id.value = profile.wx_id;
    }

    // 获取微信账号列表
    const res = await getWxListByaccount({ account: currentUsername });
    if (res.data.length && Array.isArray(res.data)) {
      personalList.value = res.data;
      totalPersonCount.value = res.data.length;
      onlinePersonCount.value = res.data.filter((item) => item.isOnline).length;
      if (personalList.value.length > 0) {
        await getPendingFriends(personalList.value[0].wx_id);
      }
      // 设置第一个账号为当前账号
      if (personalList.value.length > 0) {
        const firstAccount = personalList.value[0];
        const msgprofile = { wx_id: firstAccount.wx_id };
        msgprofilewx_id.value = firstAccount.wx_id;
        localStorage.setItem('msgprofile', JSON.stringify(msgprofile));
      }
    } else {
      localStorage.removeItem('msgprofile');
      localStorage.removeItem('wxLogin');
      return;
    }

    const result = await msgprofile({ wx_id: msgprofilewx_id.value });
    if (result.data?.data) {
      wxProfile.value = result.data.data;
      msgprofilewx_id.value = result.data.data.wx_id;
      localStorage.setItem('msgprofile', JSON.stringify(result.data.data));
      personalList.value[0] = result.data.data;
    }

    // 只有登录成功且有 wx_id 时才连接 WebSocket
    if (personalList.value.length > 0 && msgprofilewx_id.value) {
      await connectWebSocket();
      websocket.setMessageCallback(getMessageCallback);
    }
    handleClick(messageListType.value);
    await getMessgeStation();
  } catch (error) {
    console.error('请扫码登录微信:', error);
    // ElMessage.error('请扫码登录微信');
  }
};

// 修改 WebSocket 相关函数
const connectWebSocket = async () => {
  try {
    if (!msgprofilewx_id.value) {
      throw new Error('微信ID未初始化');
    }
    await new Promise((resolve) => {
      websocket.Init(msgprofilewx_id.value);
      websocket.getWebSocket().onopen = () => {
        console.log('WebSocket连接成功');
        resolve(true);
      };
    });
  } catch (error) {
    console.error('WebSocket连接失败:', error);
    // ElMessage.error('WebSocket连接失败');
  }
};

// 修改获取用户列表函数
const getUserList = async () => {
  if (!msgprofilewx_id.value) {
    ElMessage.warning('请先登录微信');
    return;
  }

  try {
    const res = await msgcontacts({ wxId: msgprofilewx_id.value });
    usersSections.value = res.data.data.mapList;
    usersSections.value.forEach((item: any) => {
      item.value.forEach((ele: any) => {
        ele.checked = false;
      });
    });
  } catch (error) {
    console.error('获取联系人列表失败:', error);
    ElMessage.error('获取联系人列表失败');
  }
};

// 修改获取群组列表函数
const getGroupList = async () => {
  if (!msgprofilewx_id.value) {
    ElMessage.warning('请先登录微信');
    return;
  }

  try {
    const res = await getGroupContacts({ wxId: msgprofilewx_id.value });
    if (res.data) {
      groupSections.value = [
        {
          id: 1,
          key: '群聊',
          value: res.data.map((group: any) => ({
            wx_id: group.id,
            nick_name: group.group_name,
            avatar_url: '',
            group_id: group.id,
            member_count: group.group_member_count,
            create_time: group.group_create_time,
            wechat_account_id: group.wechat_account_id,
            groupUrlList: group.groupUrlList
          }))
        }
      ];
    }
  } catch (error) {
    console.error('获取群聊列表失败:', error);
    ElMessage.error('获取群聊列表失败');
  }
};

// 修改消息状态获取函数
const getMessgeStation = async () => {
  scrollToBottom();

  try {
    const params = {
      wxId: msgprofilewx_id.value,
      sendWxId: messageContent.value.wx_id,
      ...(messageContent.value.group_id ? { group_id: messageContent.value.group_id } : {})
    };
    const res = await msgSendConversations(params);
    conversations.value = res.data;
  } catch (error) {
    console.error('获取消息状态失败:', error);
    ElMessage.error('获取消息状态失败');
  }
};

// 修改 onMounted 钩子
onMounted(async () => {
  try {
    await initWxProfile();
    // 初始化过滤数据
    initFilteredData();

    // 添加页面可见性监听
    setupVisibilityListener();

    // 添加WebSocket状态监控
    setupWebSocketMonitor();
  } catch (error) {
    console.error('页面初始化失败:', error);
    ElMessage.error('页面初始化失败');
  } finally {
    // 无论成功还是失败，都关闭加载状态
    isPageLoading.value = false;
  }
});
onBeforeUnmount(() => {
  disconnectWebSocket();
  websocket.setMessageCallback(null);

  // 清理刷新倒计时定时器
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
});
// 连接WebSocket
const disconnectWebSocket = () => {
  websocket.Close();
};
const scrollToBottom = () => {
  nextTick(() => {
    if (scrollbarRef.value) {
      const scrollbar = scrollbarRef.value;
      scrollbar.scrollTop = scrollbar.scrollHeight;
    }
  });
};
const handleClick = async (type: string) => {
  messageListType.value = type;
  if (type === 'message') {
    messageIcon.value = messageActive;
    usersIcon.value = users;
    adduserIcon.value = adduser;
    groupIcon.value = group;
    getMessgeStation();
  } else if (type === 'users') {
    messageIcon.value = message;
    usersIcon.value = usersActive;
    adduserIcon.value = adduser;
    groupIcon.value = group;
    getUserList();
  } else if (type === 'adduser') {
    messageIcon.value = message;
    usersIcon.value = users;
    adduserIcon.value = adduserActive;
    groupIcon.value = group;
    // 获取待添加好友列表
    if (personalList.value.length > 0) {
      console.log('切换到待添加好友标签，当前登录的微信ID:', personalList.value[0].wx_id);
      await updateAddFriends();
      await getPendingFriends(personalList.value[0].wx_id);
    } else {
      console.warn('没有登录的微信账号');
      ElMessage.warning('请先登录微信账号');
    }
  } else if (type === 'group') {
    messageIcon.value = message;
    usersIcon.value = users;
    adduserIcon.value = adduser;
    groupIcon.value = groupActive;
    getGroupList();
  }
  // messageBody.value = [];
};
const updateAddFriends = async () => {
  if (!personalList.value?.[0]?.wx_id) {
    console.warn('未找到当前登录的微信ID');
    return;
  }

  try {
    await updateWechatFriends(personalList.value[0].wx_id);
  } catch (error) {
    console.error('更新好友列表未读状态失败:', error);
    ElMessage.error('更新好友列表未读状态失败');
  }
};
const isGroupCreating = ref(false);
const isExitingGroup = ref(false);

// 邀请好友进群相关状态
const inviteDialogVisible = ref(false);
const inviteLoading = ref(false);
const selectedFriendsForInvite = ref<any[]>([]);
const inviteFriendSearchKeyword = ref('');
const creatGroup = () => {
  let data = {
    wxIdList: '',
    createBy: msgprofilewx_id.value
  };
  usersSections.value.forEach((item: any) => {
    item.value.forEach((ele: any) => {
      if (ele.checked) {
        data.wxIdList += ele.wx_id + ',';
      }
    });
  });

  isGroupCreating.value = true;
  msggroupcreate(data)
    .then((res) => {
      isGroupCreating.value = false;
      if (res.data && res.data.data.chat_room_id) {
        // 恢复创建状态
        isCreatGroup.value = false;

        // 清除所有选中状态
        usersSections.value.forEach((item: any) => {
          item.value.forEach((ele: any) => {
            ele.checked = false;
          });
        });

        // 弹窗提示创建成功
        ElMessage.success('群聊创建成功');

        // 切换到消息列表页
        handleClick('message');
        const newGroupId = res.data.data.chat_room_id;
        getMessgeStation2({ group_id: newGroupId });
      } else {
        ElMessage.error('创建群聊失败');
      }
    })
    .catch((error) => {
      isGroupCreating.value = false;
      console.error('创建群聊失败:', error);
      ElMessage.error('创建群聊失败');
    });
};
const handleClickUserContent = (element: any) => {
  if (isCreatGroup.value) {
    return;
  } else {
    // 切换对话时清空消息输入框和@成员
    senMessageContent.value = '';
    selectedAtMembers.value = [];
    showAtMemberSelector.value = false;
    atSearchKeyword.value = '';

    messageContent.value = { ...element };
    handleClick('message');
    getMessageContet();
    getMessgeStation3(element);
  }
};
const getMessgeStation3 = async (element: any) => {
  isMessageLoading.value = true;
  // 等待 DOM 渲染后滚动到底部
  await nextTick();
  scrollToBottom();
  try {
    const params = {
      wxId: msgprofilewx_id.value,
      sendWxId: messageContent.value.wx_id,
      ...(messageContent.value.group_id ? { group_id: messageContent.value.group_id } : {})
    };
    const res = await msgSendConversations(params);
    conversations.value = res.data;
    let found = false;
    conversations.value.forEach((section: any, sectionIdx: number) => {
      if (section.groupName === '消息列表') {
        section.data.forEach((item: any) => {
          if (!found && (item.user_id === element.wx_id || item.wx_id === element.wx_id)) {
            conversations.value.forEach((sec: any) => {
              sec.data.forEach((itm: any) => (itm.isShow = false));
            });
            item.isShow = true;
            handleClickMessage(item, sectionIdx);
            found = true;
          }
        });
      }
    });
  } catch (error) {
    console.error('获取消息状态失败:', error);
    ElMessage.error('获取消息状态失败');
  }
};
const handleClickGroupContent = async (element: any) => {
  // 切换对话时清空消息输入框和@成员
  senMessageContent.value = '';
  selectedAtMembers.value = [];
  showAtMemberSelector.value = false;
  atSearchKeyword.value = '';

  messageContent.value = { ...element };
  nowExprentTag.value = '群聊';
  await handleClick('group');
  await getMessageContet();
  await getMessgeStation2(element);
};
const getMessgeStation2 = async (element: any, retryCount = 0) => {
  const MAX_RETRY = 5;
  isMessageLoading.value = true;
  // 等待 DOM 渲染后滚动到底部
  await nextTick();
  scrollToBottom();
  try {
    const params = {
      wxId: msgprofilewx_id.value,
      sendWxId: messageContent.value.wx_id,
      ...(messageContent.value.group_id ? { group_id: messageContent.value.group_id } : {})
    };
    const res = await msgSendConversations(params);
    conversations.value = res.data;
    // 最后再查找 conversations 并调用 handleClickMessage
    let found = false;
    conversations.value.forEach((section: any, sectionIdx: number) => {
      if (section.groupName === '群聊') {
        section.data.forEach((item: any) => {
          if (!found && item.group_id === element.group_id) {
            handleClickMessage(item, sectionIdx);
            found = true;
          }
        });
      }
    });
    if (!found) {
      if (retryCount < MAX_RETRY) {
        await getMessgeStation2(element, retryCount + 1);
      } else {
        isMessageLoading.value = false;
        isGroupCreating.value = false;
        ElMessage.error('获取群聊消息状态失败，请稍后重试');
      }
    }
  } catch (error) {
    console.error('获取消息状态失败:', error);
    ElMessage.error('获取消息状态失败');
  }
};

const getMessageContet = () => {
  // 重置分页状态
  msgcurrent.value = '1';
  hasMore.value = true;
  isLoading.value = false;
  loadError.value = false;
  hasTriedLoadMore.value = false; // 重置加载更多标记
  shouldAutoScroll.value = true; // 初始化时允许自动滚动

  let params = {
    wxId: msgprofilewx_id.value,
    current: msgcurrent.value,
    size: msgsize.value,
    ...(nowExprentTag.value === '群聊' ? { group_id: messageContent.value.group_id } : { sendWxId: messageContent.value.wx_id })
  };

  msgSendMessages(params)
    .then((res) => {
      messageListType.value = 'message';
      const responseData = res.data.records || res.data;
      messageBody.value = processMessageList(responseData.reverse());
      // 判断是否还有更多消息：如果返回的消息数量等于请求的数量，说明可能还有更多
      hasMore.value = responseData.length === parseInt(msgsize.value);
    })
    .catch((error) => {
      console.error('获取消息内容失败:', error);
      ElMessage.error('获取消息内容失败');
    });
};
const handleClickFile = () => {
  if (fileInput.value) {
    fileInput.value.value = '';
    fileInput.value.click();
  }
};
const handleFileChange = async (event: any) => {
  const file = event.target.files[0];
  console.log(event);

  if (!file) return;

  // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
    // 清空文件输入框
    if (event.target) {
      event.target.value = '';
    }
    return;
  }

  isFileUploading.value = true;

  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('wxId', messageContent.value.wx_id);
    formData.append('sendWxId', msgprofilewx_id.value);

    // 根据文件类型选择不同的API
    if (file.type.startsWith('image/') || file.type.startsWith('video/')) {
      // 图片和视频使用 msgSendImage
      await msgSendImage(formData);
      ElMessage.success('图片/视频发送成功，正在加载中...');
    } else {
      // 其他文件使用 msgSendFile
      await msgSendFile(formData);
      ElMessage.success('文件发送成功，正在加载中...');
    }
  } catch (error: any) {
    // 处理后台返回的错误信息
    let errorMessage = '文件发送失败';
    if (error) {
      if (error.response && error.response.data && error.response.data.msg) {
        // axios 错误响应格式
        errorMessage = error.response.data.msg;
      } else if (error.msg) {
        // 直接的错误对象格式
        errorMessage = error.msg;
      } else if (error.message) {
        // 标准错误对象格式
        errorMessage = error.message;
      }
    }
    ElMessage.error(errorMessage);
  } finally {
    isFileUploading.value = false;
  }
};
const checkMore = () => {
  isShowCheck.value = !isShowCheck.value;
  if (isShowCheck.value) {
    messageBody.value.forEach((item: any) => {
      item.isShowCheck = true;
    });
  } else {
    messageBody.value.forEach((item: any) => {
      item.isShowCheck = false;
    });
  }
};
const sendMessage = async (content: string) => {
  if (!msgprofilewx_id.value) {
    ElMessage.warning('请先登录微信');
    return;
  }

  if (!content.trim()) {
    ElMessage.warning('请输入消息内容');
    return;
  }

  // 检查消息长度限制
  if (content.trim().length > 2000) {
    ElMessage.warning('消息内容不能超过2000个字符');
    return;
  }
  try {
    // 处理消息内容，在@用户名后添加\u2005字符
    let processedContent = content;
    if (messageContent.value.group_id && selectedAtMembers.value.length > 0) {
      // 为每个@的成员在用户名后添加\u2005字符
      selectedAtMembers.value.forEach((member) => {
        const atText = `@${member.user_name}`;
        const atTextWithSpace = `@${member.user_name}\u2005`;
        processedContent = processedContent.replace(new RegExp(atText, 'g'), atTextWithSpace);
      });
    }

    const params: any = {
      wxId: messageContent.value.wx_id,
      sendWxId: msgprofilewx_id.value,
      msg: processedContent,
      ...(messageContent.value.group_id ? { myWxId: msgprofilewx_id.value } : {})
    };

    // 如果是群聊且有@的成员，添加atList参数
    if (messageContent.value.group_id && selectedAtMembers.value.length > 0) {
      // 将@的成员ID用逗号拼接
      params.atList = selectedAtMembers.value.map((member) => member.user_id).join(',');
    }

    console.log(params);
    await websocket.Send(params);
    await getMessgeStation();
    senMessageContent.value = '';

    // 清空@的成员列表
    selectedAtMembers.value = [];
    showAtMemberSelector.value = false;
    atSearchKeyword.value = '';

    // 发送消息后，重置分页状态并滚动到底部
    msgcurrent.value = '1';
    hasMore.value = true;
    loadError.value = false;
    hasTriedLoadMore.value = false;
    shouldAutoScroll.value = true; // 发送消息时允许自动滚动

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败');
  }
};
const addNewAcount = () => {
  dialogAddAccount.value = true;
  generateQrcode();
};
const generateQrcode = async () => {
  try {
    // 重置状态
    qrcodeUrl.value = '';
    qrcodeStatus.value = null;
    isQrcodeError.value = false;
    isQrcodeExpired.value = false;
    qrcodeCountdown.value = 30;

    // 清除之前的定时器
    if (qrcodeTimer.value) {
      clearInterval(qrcodeTimer.value);
      qrcodeTimer.value = null;
    }
    if (qrcodeExpireTimer.value) {
      clearInterval(qrcodeExpireTimer.value);
      qrcodeExpireTimer.value = null;
    }

    // 先获取登录端口号
    const loginRes = await msgGetWxLogin();
    if (!loginRes.data) {
      ElMessage.error('获取登录端口失败');
      isQrcodeError.value = true;
      return;
    }
    // 不立即存储 wxLogin 到 localStorage，等待登录状态确认后再存储
    console.log('登录端口号:', loginRes.data);

    // 调用获取二维码接口
    const res = await msgGetQrcode({ wxLogin: loginRes.data });
    if (res.data) {
      qrcodeUrl.value = imageUrlfirst + res.data;
      startQrcodeCheck(loginRes.data);
      startQrcodeExpireCountdown();
    } else {
      ElMessage.error('获取二维码失败，请刷新二维码');
      isQrcodeError.value = true;
      qrcodeStatus.value = {
        icon: 'Warning',
        text: '获取二维码失败，请刷新二维码',
        color: '#E6A23C'
      };
    }
  } catch (error) {
    console.error('获取二维码失败:', error);
    ElMessage.error('获取二维码失败，请刷新二维码');
    isQrcodeError.value = true;
    qrcodeStatus.value = {
      icon: 'Warning',
      text: '获取二维码失败，请刷新二维码',
      color: '#E6A23C'
    };
  }
};
const startQrcodeCheck = (wxLogin: string) => {
  // 清除之前的定时器
  if (qrcodeTimer.value) {
    clearInterval(qrcodeTimer.value);
  }

  // 开始轮询检查二维码状态
  qrcodeTimer.value = window.setInterval(async () => {
    // 如果二维码已过期，停止检查
    if (isQrcodeExpired.value) {
      if (qrcodeTimer.value) {
        clearInterval(qrcodeTimer.value);
        qrcodeTimer.value = null;
      }
      return;
    }

    try {
      const res = await msgGetWxLoginStatus({ wxLogin, account: currentUsername });
      if (res.data.data.status === 1) {
        // 登录成功，此时才缓存 wxLogin 到 localStorage
        localStorage.setItem('wxLogin', wxLogin);

        qrcodeStatus.value = {
          icon: 'Check',
          text: '已确认登录',
          color: '#67C23A'
        };
        handleLoginSuccess();
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
    }
  }, 2000);
};

// 开始二维码过期倒计时
const startQrcodeExpireCountdown = () => {
  // 清除之前的过期定时器
  if (qrcodeExpireTimer.value) {
    clearInterval(qrcodeExpireTimer.value);
  }

  // 开始倒计时
  qrcodeExpireTimer.value = window.setInterval(() => {
    qrcodeCountdown.value--;

    if (qrcodeCountdown.value <= 0) {
      // 倒计时结束，标记为过期
      isQrcodeExpired.value = true;
      qrcodeCountdown.value = 0;

      // 清除倒计时定时器
      if (qrcodeExpireTimer.value) {
        clearInterval(qrcodeExpireTimer.value);
        qrcodeExpireTimer.value = null;
      }

      // 停止登录状态检查
      if (qrcodeTimer.value) {
        clearInterval(qrcodeTimer.value);
        qrcodeTimer.value = null;
      }

      // 显示过期提示
      ElMessage.warning('二维码已过期，请刷新二维码');
    }
  }, 1000);
};
const handleLoginSuccess = async () => {
  // 清除所有定时器
  if (qrcodeTimer.value) {
    clearInterval(qrcodeTimer.value);
    qrcodeTimer.value = null;
  }
  if (qrcodeExpireTimer.value) {
    clearInterval(qrcodeExpireTimer.value);
    qrcodeExpireTimer.value = null;
  }

  try {
    // 获取账号列表
    const res = await getWxListByaccount({ account: currentUsername });
    if (res.data.length && Array.isArray(res.data)) {
      personalList.value = res.data;
      totalPersonCount.value = res.data.length;
      onlinePersonCount.value = res.data.filter((item) => item.isOnline).length;
      // 设置第一个账号为当前账号
      if (personalList.value.length > 0) {
        const firstAccount = personalList.value[0];
        const msgprofile = { wx_id: firstAccount.wx_id };
        msgprofilewx_id.value = firstAccount.wx_id;
        localStorage.setItem('msgprofile', JSON.stringify(msgprofile));

        // 登录成功后初始化数据
        console.log('开始初始化登录后数据...');

        // 获取消息列表
        await getMessgeStation();
        console.log('消息列表获取完成');

        // 获取联系人列表
        await getUserList();
        console.log('联系人列表获取完成');

        // 获取群聊列表
        await getGroupList();
        console.log('群聊列表获取完成');

        // 断开旧连接并重新连接 WebSocket
        disconnectWebSocket();
        await connectWebSocket();
        websocket.setMessageCallback(getMessageCallback);
        console.log('WebSocket连接完成');
      }
    }

    // 关闭弹窗
    dialogAddAccount.value = false;
    ElMessage.success('登录成功');
  } catch (error) {
    dialogAddAccount.value = false;
    console.error('登录后初始化失败:', error);
    // ElMessage.error('登录后初始化失败');
  }
};
// 监听弹窗关闭
watch(dialogAddAccount, (newVal) => {
  if (!newVal) {
    // 清除所有定时器
    if (qrcodeTimer.value) {
      clearInterval(qrcodeTimer.value);
      qrcodeTimer.value = null;
    }
    if (qrcodeExpireTimer.value) {
      clearInterval(qrcodeExpireTimer.value);
      qrcodeExpireTimer.value = null;
    }
    // 重置状态
    qrcodeUrl.value = '';
    qrcodeStatus.value = null;
    isQrcodeError.value = false;
    isQrcodeExpired.value = false;
    qrcodeCountdown.value = 30;
  }
});
const saveAitype = () => {
  let params = {
    aiType: radioChange.value,
    wxId: msgprofilewx_id.value,
    sendWxId: messageContent.value.wx_id
  };

  msgupdateAiType(params).then((res) => {
    ElMessage.success('保存成功');
    getMessgeStation();
  });
};
const copyMessage = (content: string) => {
  // 实现复制消息的逻辑
  console.log('复制消息:', content);
};
const forwardMessage = (item: any) => {
  // 实现转发消息的逻辑
  console.log('转发消息:', item);
};
const quoteMessage = (item: any) => {
  // 实现引用消息的逻辑
  console.log('引用消息:', item);
};
const iconList = {
  message: { default: message, active: messageActive },
  users: { default: users, active: usersActive },
  group: { default: group, active: groupActive },
  adduser: { default: adduser, active: adduserActive }
};

const iconLabels = {
  message: '消息',
  users: '联系人',
  group: '群聊',
  adduser: '添加'
};

// 搜索相关函数
const getSearchPlaceholder = () => {
  const placeholders = {
    message: '搜索消息、联系人...',
    users: '搜索联系人、手机号...',
    group: '搜索群聊...',
    adduser: '搜索好友请求...'
  };
  return placeholders[messageListType.value as keyof typeof placeholders] || '搜索...';
};

// 搜索处理函数
const handleSearch = () => {
  const keyword = searchInput.value.toLowerCase().trim();

  switch (messageListType.value) {
    case 'message':
      filterConversations(keyword);
      break;
    case 'users':
      filterUsersSections(keyword);
      break;
    case 'group':
      filterGroupSections(keyword);
      break;
    case 'adduser':
      filterAdduserSections(keyword);
      break;
  }
};

// 防抖搜索函数
let searchTimeout: NodeJS.Timeout | null = null;
const debouncedSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }
  searchTimeout = setTimeout(() => {
    handleSearch();
  }, 300);
};

// 清空搜索处理函数
const handleClearSearch = () => {
  searchInput.value = '';
  initFilteredData();
};

// 过滤消息列表
const filterConversations = (keyword: string) => {
  if (!keyword) {
    filteredConversations.value = conversations.value;
    return;
  }

  filteredConversations.value = conversations.value
    .map((section: any) => ({
      ...section,
      data: section.data.filter(
        (item: any) =>
          item.receiverName?.toLowerCase().includes(keyword) ||
          item.last_message?.toLowerCase().includes(keyword) ||
          item.nick_name?.toLowerCase().includes(keyword)
      )
    }))
    .filter((section: any) => section.data.length > 0);
};

// 过滤联系人列表
const filterUsersSections = (keyword: string) => {
  if (!keyword) {
    filteredUsersSections.value = usersSections.value;
    return;
  }

  filteredUsersSections.value = usersSections.value
    .map((section: any) => ({
      ...section,
      value: section.value.filter((item: any) => item.nick_name?.toLowerCase().includes(keyword) || item.wx_account?.toLowerCase().includes(keyword))
    }))
    .filter((section: any) => section.value.length > 0);
};

// 过滤群聊列表
const filterGroupSections = (keyword: string) => {
  if (!keyword) {
    filteredGroupSections.value = groupSections.value;
    return;
  }

  filteredGroupSections.value = groupSections.value
    .map((section: any) => ({
      ...section,
      value: section.value.filter((item: any) => item.nick_name?.toLowerCase().includes(keyword))
    }))
    .filter((section: any) => section.value.length > 0);
};

// 过滤好友请求列表
const filterAdduserSections = (keyword: string) => {
  if (!keyword) {
    filteredAdduserSections.value = adduserSections.value;
    return;
  }

  filteredAdduserSections.value = adduserSections.value
    .map((section: any) => ({
      ...section,
      value: section.value.filter((item: any) => item.fromnickname?.toLowerCase().includes(keyword) || item.content?.toLowerCase().includes(keyword))
    }))
    .filter((section: any) => section.value.length > 0);
};

// 初始化过滤数据
const initFilteredData = () => {
  filteredConversations.value = conversations.value;
  filteredUsersSections.value = usersSections.value;
  filteredGroupSections.value = groupSections.value;
  filteredAdduserSections.value = adduserSections.value;
};

// 监听数据变化，同步更新过滤数据
watch([conversations, usersSections, groupSections, adduserSections], () => {
  if (!searchInput.value) {
    initFilteredData();
  } else {
    handleSearch();
  }
});

// 监听搜索输入变化
watch(searchInput, () => {
  debouncedSearch();
});

// 监听列表类型变化，清空搜索
watch(messageListType, () => {
  searchInput.value = '';
  initFilteredData();
});

const formatMessageContent = (content: any) => {
  // 将换行符转换为 <br> 标签
  return content.replace(/\n/g, '<br>');
};

interface QrcodeStatus {
  icon: string;
  text: string;
  color: string;
}

const qrcodeUrl = ref('');
const qrcodeStatus = ref<QrcodeStatus | null>(null);
const qrcodeTimer = ref<number | null>(null);
const qrcodeExpireTimer = ref<number | null>(null);
const isQrcodeExpired = ref(false);
const qrcodeCountdown = ref(30);

interface MessageItem {
  message_content?: string;
  message_type: number;
  direction: string;
  senderUrl: string;
  messageId: string;
  isShowCheck?: boolean;
  isLoading?: boolean;
  aiMessage?: string;
  ai_message?: string;
}

// 定义表情符号映射类型
type WechatEmojiKey = string;

// 处理消息内容中的表情符号
const processMessageContent = (content: string): string => {
  try {
    return content.replace(/\$\$([^$]+)\]/g, (match: string) => {
      return wechatEmojiMap[match as WechatEmojiKey] || match;
    });
  } catch (error) {
    console.error('处理消息内容时出错:', error);
    return content;
  }
};

// 处理消息列表
const processMessageList = (messages: MessageItem[]): MessageItem[] => {
  return messages.map((item) => {
    if (item.message_content) {
      return {
        ...item,
        message_content: processMessageContent(item.message_content)
      };
    }
    return item;
  });
};

// 标签管理相关
const tagDialogVisible = ref(false);
const selectedTags = ref<Tag[]>([]);
const newTag = ref('');

// 名称修改相关
const editFriendNameDialogVisible = ref(false);
const editGroupNameDialogVisible = ref(false);
const editFriendNameLoading = ref(false);
const editGroupNameLoading = ref(false);

// 编辑客户信息相关
const editCustomerDialogVisible = ref(false);
const editCustomerLoading = ref(false);
const editCustomerFormRef = ref();

// 折叠状态控制
const isBasicInfoExpanded = ref(false);
const isTagsExpanded = ref(false);
const isGroupTagsExpanded = ref(false);
const isGroupMembersExpanded = ref(false);
const showAllGroupMembers = ref(false);
const isMedicationReminderExpanded = ref(false);
const isPurchaseRecordExpanded = ref(false);
const editCustomerForm = reactive({
  age: '',
  gender: '',
  birthday: '',
  phone: '',
  qq: '',
  email: '',
  address: '',
  description: ''
});
const editCustomerFormRules = {
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  qq: [{ pattern: /^[1-9][0-9]{4,}$/, message: '请输入正确的QQ号码', trigger: 'blur' }]
};

// 购买记录相关
const purchaseRecordDialogVisible = ref(false);
const purchaseRecordLoading = ref(false);
const purchaseRecordList = ref<any[]>([]);
const purchaseRecordTotal = ref(0);
const currentUserWxId = ref('');

// 购买记录表单相关
const purchaseRecordFormDialogVisible = ref(false);
const purchaseRecordFormLoading = ref(false);
const purchaseRecordFormRef = ref();
const purchaseRecordFormMode = ref<'add' | 'edit'>('add');
const currentEditIndex = ref(-1);
const purchaseRecordForm = reactive({
  id: undefined,
  wxId: '',
  myWxId: '',
  shopName: '',
  orderNo: '',
  receiverName: '',
  receiverPhone: '',
  receiverAddr: '',
  orderDate: undefined,
  productName: '',
  productCode: '',
  productSpec: '',
  quantity: undefined,
  remark: ''
});
const purchaseRecordFormRules = {
  shopName: [{ required: true, message: '请输入店铺名称+平台', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  receiverName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入收件人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入购买数量', trigger: 'blur' }]
};

// 用药提醒相关
const medicationReminderDialogVisible = ref(false);
const medicationReminderLoading = ref(false);
const customerMedicationReminder = ref<any>(null);
const medicationReminderFormRef = ref();

// 间隔天数相关变量
const dayType = ref<'daily' | 'custom'>('daily');
const customDayValue = ref<number>();

// 客服好友选择相关变量
const customerServiceFriendSelectDialogVisible = ref(false);
const selectedCustomerServiceFriends = ref<any[]>([]);
const medicationReminderForm = reactive({
  id: undefined,
  wxId: '',
  sendWxId: '',
  day: undefined as number | undefined,
  triple: undefined,
  productName: '',
  message: '',
  status: '1',
  customerService: '',
  customerServiceStatus: '0',
  deadline: ''
});
const medicationReminderFormRules = computed(() => ({
  sendWxId: [{ required: true, message: '请输入接收人微信ID', trigger: 'blur' }],
  day: [{ required: true, message: '请选择间隔天数', trigger: 'change' }],
  triple: [{ required: true, message: '请输入每天次数', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  message: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
  status: [],
  customerService:
    medicationReminderForm.customerServiceStatus === '0'
      ? [
          {
            required: true,
            validator: (rule: any, value: any, callback: any) => {
              if (medicationReminderForm.customerServiceStatus === '0' && (!value || value.trim() === '')) {
                callback(new Error('请选择所属客服'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      : [],
  customerServiceStatus: [],
  deadline: [{ required: true, message: '请选择用药截至日期', trigger: 'change' }]
}));

// 表单数据
const friendNameForm = reactive({
  name: ''
});

const groupNameForm = reactive({
  name: ''
});

// 表单验证规则
const friendNameRules = {
  name: [] // 移除必填验证，允许备注为空
};

const groupNameRules = {
  name: [{ required: true, message: '请输入群聊名称', trigger: 'blur' }]
};

// 显示修改好友备注对话框
const showEditFriendNameDialog = () => {
  friendNameForm.name = messageContent.value.remark || '';
  editFriendNameDialogVisible.value = true;
};

// 显示修改群聊名称对话框
const showEditGroupNameDialog = () => {
  groupNameForm.name = messageContent.value.nick_name || '';
  editGroupNameDialogVisible.value = true;
};

// 确认修改好友备注
const confirmEditFriendName = async () => {
  editFriendNameLoading.value = true;
  try {
    // 允许备注为空，使用 trim() 处理但不检查是否为空
    const remarkValue = friendNameForm.name.trim();
    await updateFriendName({
      sendWxId: messageContent.value.wx_id,
      wxId: msgprofilewx_id.value,
      name: remarkValue
    });

    ElMessage.success('好友备注修改成功');
    editFriendNameDialogVisible.value = false;
    // 更新本地显示
    messageContent.value.remark = remarkValue;
    messageContent.value.nick_name = remarkValue;
    setTimeout(() => {
      getMessgeStation();
    }, 1000);
  } catch (error) {
    console.error('修改好友备注失败:', error);
    ElMessage.error('修改好友备注失败');
  } finally {
    editFriendNameLoading.value = false;
  }
};

// 确认修改群聊名称
const confirmEditGroupName = async () => {
  if (!groupNameForm.name.trim()) {
    ElMessage.warning('请输入群聊名称');
    return;
  }

  editGroupNameLoading.value = true;
  try {
    await updateGroupName({
      wxId: msgprofilewx_id.value,
      name: groupNameForm.name.trim(),
      chatRoomId: messageContent.value.group_id
    });

    ElMessage.success('群聊名称修改成功');
    editGroupNameDialogVisible.value = false;
    // 更新本地显示
    messageContent.value.nick_name = groupNameForm.name.trim();
    setTimeout(() => {
      getMessgeStation();
    }, 1000);
  } catch (error) {
    console.error('修改群聊名称失败:', error);
    ElMessage.error('修改群聊名称失败');
  } finally {
    editGroupNameLoading.value = false;
  }
};

// 退出群聊
const handleExitGroup = async () => {
  if (!messageContent.value.group_id) {
    ElMessage.warning('群聊信息不完整');
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要退出群聊"${messageContent.value.nick_name}"吗？退出后将无法接收群聊消息。`, '退出群聊', {
      confirmButtonText: '确定退出',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    });

    isExitingGroup.value = true;

    await exitGroup({
      groupId: messageContent.value.group_id,
      wxId: msgprofilewx_id.value
    });

    ElMessage.success('已成功退出群聊');

    // 显示加载动画
    isPageLoading.value = true;

    // 清空当前消息内容
    messageContent.value = {
      remark: '',
      nick_name: '',
      wx_id: '',
      avatar_url: '',
      wx_account: '',
      group_id: '',
      user_id: '',
      group_member_count: 0,
      groupMembers: [],
      tags: []
    };

    // 刷新群聊列表
    await getGroupList();

    // 切换到消息列表页面（会自动调用 getMessgeStation 刷新会话列表，此时只传递 wxId）
    handleClick('message');

    // 关闭加载动画
    isPageLoading.value = false;
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('退出群聊失败:', error);

      // 处理特定的错误情况
      if (error.response && error.response.data) {
        const { code, msg } = error.response.data;
        if (code === 500 && msg === '微信已退出，无法操作') {
          ElMessage.error('微信已退出，请重新登录后再试');
          // 可以在这里触发重新登录逻辑
          return;
        }
        ElMessage.error(msg || '退出群聊失败');
      } else {
        ElMessage.error('退出群聊失败');
      }
    }
  } finally {
    isExitingGroup.value = false;
    isPageLoading.value = false;
  }
};

// 邀请好友进群
const handleInviteFriends = async () => {
  if (!messageContent.value.group_id) {
    ElMessage.warning('群聊信息不完整');
    return;
  }

  // 确保有好友列表数据
  if (usersSections.value.length === 0) {
    await getUserList();
  }

  // 清空之前的选择和搜索
  selectedFriendsForInvite.value = [];
  inviteFriendSearchKeyword.value = '';

  // 显示邀请对话框
  inviteDialogVisible.value = true;
};

// 切换好友选择状态
const toggleFriendSelection = (friend: any) => {
  const index = selectedFriendsForInvite.value.findIndex((f) => f.wx_id === friend.wx_id);
  if (index > -1) {
    selectedFriendsForInvite.value.splice(index, 1);
  } else {
    selectedFriendsForInvite.value.push(friend);
  }
};

// 从选择列表中移除好友
const removeFriendFromSelection = (friend: any) => {
  const index = selectedFriendsForInvite.value.findIndex((f) => f.wx_id === friend.wx_id);
  if (index > -1) {
    selectedFriendsForInvite.value.splice(index, 1);
  }
};

// 确认邀请好友
const confirmInviteFriends = async () => {
  if (selectedFriendsForInvite.value.length === 0) {
    ElMessage.warning('请选择要邀请的好友');
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要邀请 ${selectedFriendsForInvite.value.length} 位好友进入群聊"${messageContent.value.nick_name}"吗？`, '确认邀请', {
      confirmButtonText: '确定邀请',
      cancelButtonText: '取消',
      type: 'info'
    });

    inviteLoading.value = true;

    // 准备邀请参数
    const wxIdList = selectedFriendsForInvite.value.map((friend) => friend.wx_id).join(',');

    await inviteToGroup({
      groupId: messageContent.value.group_id,
      wxIdList: wxIdList,
      wxId: msgprofilewx_id.value
    });

    ElMessage.success(`成功邀请 ${selectedFriendsForInvite.value.length} 位好友进群`);

    // 关闭对话框并清空选择
    inviteDialogVisible.value = false;
    selectedFriendsForInvite.value = [];

    // 刷新群聊信息（可选）
    // 这里可以重新获取群成员信息
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('邀请好友进群失败:', error);

      // 处理特定的错误情况
      if (error.response && error.response.data) {
        const { msg } = error.response.data;
        ElMessage.error(msg || '邀请好友进群失败');
      } else {
        ElMessage.error('邀请好友进群失败');
      }
    }
  } finally {
    inviteLoading.value = false;
  }
};

// 编辑客户信息
const handleEditCustomer = () => {
  // 填充当前客户信息到表单
  editCustomerForm.age = messageContent.value.age || '';
  editCustomerForm.gender = messageContent.value.gender || '';
  editCustomerForm.birthday = messageContent.value.birthday || '';
  editCustomerForm.phone = messageContent.value.phone || '';
  editCustomerForm.qq = messageContent.value.qq || '';
  editCustomerForm.email = messageContent.value.email || '';
  editCustomerForm.address = messageContent.value.address || '';
  editCustomerForm.description = messageContent.value.description || '';

  editCustomerDialogVisible.value = true;
};

// 性别文本转换
const getGenderText = (gender: string | number) => {
  switch (String(gender)) {
    case '1':
      return '男';
    case '2':
      return '女';
    default:
      return '-';
  }
};

// 切换基本信息折叠状态
const toggleBasicInfo = () => {
  isBasicInfoExpanded.value = !isBasicInfoExpanded.value;
};

// 切换客户标签折叠状态
const toggleTags = () => {
  isTagsExpanded.value = !isTagsExpanded.value;
};

// 切换群聊标签折叠状态
const toggleGroupTags = () => {
  isGroupTagsExpanded.value = !isGroupTagsExpanded.value;
};

// 切换群成员列表折叠状态
const toggleGroupMembers = () => {
  isGroupMembersExpanded.value = !isGroupMembersExpanded.value;
  if (!isGroupMembersExpanded.value) {
    showAllGroupMembers.value = false;
  }
};

// 切换显示所有群成员
const toggleShowAllMembers = () => {
  showAllGroupMembers.value = !showAllGroupMembers.value;
};

// 计算显示的群成员列表
const displayedGroupMembers = computed(() => {
  if (!messageContent.value.groupMembers) return [];

  // 显示所有群成员，包括自己
  const allMembers = messageContent.value.groupMembers;

  const maxDisplayCount = 15; // 3行 × 5个 = 15个

  if (showAllGroupMembers.value) {
    return allMembers;
  } else {
    return allMembers.slice(0, maxDisplayCount);
  }
});

// 是否有更多群成员
const hasMoreMembers = computed(() => {
  if (!messageContent.value.groupMembers) return false;

  // 基于所有成员数量判断
  return messageContent.value.groupMembers.length > 15;
});

// 过滤邀请好友列表（排除已在群里的好友并支持搜索）
const filteredInviteFriends = computed(() => {
  if (usersSections.value.length === 0) return [];

  // 获取群成员的微信ID列表
  const groupMemberIds = new Set(messageContent.value.groupMembers?.map((member) => member.user_id) || []);

  return usersSections.value
    .map((section) => {
      // 过滤掉已在群里的好友
      let filteredFriends = section.value.filter((friend: any) => !groupMemberIds.has(friend.wx_id));

      // 如果有搜索关键词，进一步过滤
      if (inviteFriendSearchKeyword.value.trim()) {
        const keyword = inviteFriendSearchKeyword.value.toLowerCase().trim();
        filteredFriends = filteredFriends.filter(
          (friend: any) => friend.nick_name.toLowerCase().includes(keyword) || (friend.remark && friend.remark.toLowerCase().includes(keyword))
        );
      }

      return {
        ...section,
        value: filteredFriends
      };
    })
    .filter((section) => section.value.length > 0); // 只返回有好友的分组
});

// 切换用药提醒折叠状态
const toggleMedicationReminder = () => {
  isMedicationReminderExpanded.value = !isMedicationReminderExpanded.value;
};

// 切换购买记录折叠状态
const togglePurchaseRecord = () => {
  isPurchaseRecordExpanded.value = !isPurchaseRecordExpanded.value;
};

// 提交编辑客户信息
const submitEditCustomer = async () => {
  if (!editCustomerFormRef.value) return;

  await editCustomerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        editCustomerLoading.value = true;

        // 调用更新客户信息的API
        const updateData = {
          wechatUser: {
            id: messageContent.value.wx_id, // 使用 wx_id 作为标识
            userName: messageContent.value.nick_name,
            userAge: editCustomerForm.age ? Number(editCustomerForm.age) : undefined,
            userGender: editCustomerForm.gender,
            userBirthday: editCustomerForm.birthday ? dayjs(editCustomerForm.birthday).format('YYYY-MM-DD') : '',
            userPhone: editCustomerForm.phone,
            userQq: editCustomerForm.qq,
            userEmail: editCustomerForm.email,
            userAddress: editCustomerForm.address,
            userDescription: editCustomerForm.description,
            wxAccount: messageContent.value.wx_id,
            type: '1', // 默认为好友类型
            remark: messageContent.value.remark || '',
            myWxId: msgprofilewx_id.value
          }
        };

        // 导入并调用更新API
        const { updateWechatUser } = await import('@/api/userMange/userMangePath');
        const res = await updateWechatUser(updateData);
        const response = res as any;

        if (response.code === 200) {
          ElMessage.success('客户信息更新成功');
          editCustomerDialogVisible.value = false;

          // 更新本地显示的客户信息
          messageContent.value.age = editCustomerForm.age;
          messageContent.value.gender = editCustomerForm.gender;
          messageContent.value.birthday = editCustomerForm.birthday;
          messageContent.value.phone = editCustomerForm.phone;
          messageContent.value.qq = editCustomerForm.qq;
          messageContent.value.email = editCustomerForm.email;
          messageContent.value.address = editCustomerForm.address;
          messageContent.value.description = editCustomerForm.description;
        } else {
          ElMessage.error(response.msg || '更新客户信息失败');
        }
      } catch (error) {
        console.error('更新客户信息失败:', error);
        ElMessage.error('更新客户信息失败');
      } finally {
        editCustomerLoading.value = false;
      }
    }
  });
};

// 购买记录相关方法
const handlePurchaseRecord = async () => {
  currentUserWxId.value = messageContent.value.wx_id;
  purchaseRecordDialogVisible.value = true;
  await loadPurchaseRecordList();
};

const loadPurchaseRecordList = async () => {
  try {
    purchaseRecordLoading.value = true;
    // 导入并调用购买记录API
    const { getPurchaseRecordList } = await import('@/api/userMange/userMangePath');
    const params: any = {
      current: 1,
      size: 50, // 获取更多记录用于外部展示
      wxId: currentUserWxId.value,
      myWxId: msgprofilewx_id.value
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await getPurchaseRecordList(params);
    const res = response as any;
    if (res.code === 200) {
      purchaseRecordList.value = res.data?.records || [];
      purchaseRecordTotal.value = res.data?.total || 0;
    } else {
      ElMessage.error(res.msg || '获取购买记录失败');
    }
  } catch (error) {
    console.error('获取购买记录失败:', error);
    ElMessage.error('获取购买记录失败');
  } finally {
    purchaseRecordLoading.value = false;
  }
};

// 新增记录
const handleAddPurchaseRecord = () => {
  purchaseRecordFormMode.value = 'add';
  currentEditIndex.value = -1;
  currentUserWxId.value = messageContent.value.wx_id; // 确保设置当前用户的wxId
  Object.assign(purchaseRecordForm, {
    id: undefined,
    wxId: currentUserWxId.value,
    myWxId: msgprofilewx_id.value,
    shopName: '',
    orderNo: '',
    receiverName: '',
    receiverPhone: '',
    receiverAddr: '',
    orderDate: undefined,
    productName: '',
    productCode: '',
    productSpec: '',
    quantity: undefined,
    remark: ''
  });
  purchaseRecordFormDialogVisible.value = true;
};

// 编辑购买记录
const handleEditPurchaseRecord = (row: any, index: number) => {
  purchaseRecordFormMode.value = 'edit';
  currentEditIndex.value = index;

  // 填充表单数据
  Object.assign(purchaseRecordForm, {
    ...row,
    myWxId: msgprofilewx_id.value,
    orderDate: row.orderDate ? new Date(row.orderDate) : undefined
  });

  purchaseRecordFormDialogVisible.value = true;
};

// 删除购买记录
const handleDeletePurchaseRecord = async (row: any, index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条购买记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 调用删除API
    const { deletePurchaseRecord } = await import('@/api/userMange/userMangePath');
    const res = await deletePurchaseRecord(row.id);
    const response = res as any;

    if (response.code === 200) {
      ElMessage.success('删除成功');
      // 确保使用正确的wxId重新加载列表
      currentUserWxId.value = messageContent.value.wx_id;
      await loadPurchaseRecordList();
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除购买记录失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 提交购买记录表单
const submitPurchaseRecordForm = async () => {
  if (!purchaseRecordFormRef.value) return;

  await purchaseRecordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        purchaseRecordFormLoading.value = true;

        const formData = {
          ...purchaseRecordForm,
          orderDate: purchaseRecordForm.orderDate ? dayjs(purchaseRecordForm.orderDate).format('YYYY-MM-DD') : undefined
        };

        const { addPurchaseRecord, updatePurchaseRecord } = await import('@/api/userMange/userMangePath');
        const response = purchaseRecordFormMode.value === 'add' ? await addPurchaseRecord(formData) : await updatePurchaseRecord(formData);

        const res = response as any;
        if (res.code === 200) {
          ElMessage.success(purchaseRecordFormMode.value === 'add' ? '新增成功' : '编辑成功');
          purchaseRecordFormDialogVisible.value = false;
          // 确保使用正确的wxId重新加载列表
          currentUserWxId.value = messageContent.value.wx_id;
          await loadPurchaseRecordList();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }

        purchaseRecordFormDialogVisible.value = false;
      } catch (error) {
        console.error('保存购买记录失败:', error);
        ElMessage.error('保存失败');
      } finally {
        purchaseRecordFormLoading.value = false;
      }
    }
  });
};

// 查看全部购买记录
const handleViewAllRecords = async () => {
  currentUserWxId.value = messageContent.value.wx_id;
  purchaseRecordDialogVisible.value = true;
  await loadPurchaseRecordList();
};

// 用药提醒相关方法
const handleMedicationReminder = async () => {
  currentUserWxId.value = messageContent.value.wx_id;

  // 如果已有用药提醒，填充表单
  if (customerMedicationReminder.value) {
    Object.assign(medicationReminderForm, {
      ...customerMedicationReminder.value,
      wxId: msgprofilewx_id.value,
      sendWxId: currentUserWxId.value,
      deadline: customerMedicationReminder.value.deadline ? new Date(customerMedicationReminder.value.deadline) : ''
    });

    // 处理间隔天数的回显
    if (customerMedicationReminder.value.day === 0) {
      dayType.value = 'daily';
      customDayValue.value = undefined;
    } else {
      dayType.value = 'custom';
      customDayValue.value = customerMedicationReminder.value.day;
    }

    // 处理客服好友的回显
    if (customerMedicationReminder.value.customerServiceList && customerMedicationReminder.value.customerServiceList.length > 0) {
      // 使用返回的 customerServiceList 数组来构建好友信息
      selectedCustomerServiceFriends.value = customerMedicationReminder.value.customerServiceList.map((service: any) => ({
        wx_id: service.customerService,
        nick_name: service.customerServiceName,
        first_nick_name: service.customerServiceName,
        avatar: '',
        gender: '',
        labels: []
      }));
    } else if (customerMedicationReminder.value.customerService) {
      // 兼容旧格式：如果没有 customerServiceList 但有 customerService 字段
      const customerServiceIds = customerMedicationReminder.value.customerService.split(',').filter((id: string) => id.trim());
      const customerServiceNames = customerMedicationReminder.value.customerServiceName ? customerMedicationReminder.value.customerServiceName.split(',') : [];
      selectedCustomerServiceFriends.value = customerServiceIds.map((wxId: string, index: number) => ({
        wx_id: wxId.trim(),
        nick_name: customerServiceNames[index] ? customerServiceNames[index].trim() : wxId.trim(),
        first_nick_name: customerServiceNames[index] ? customerServiceNames[index].trim() : wxId.trim(),
        avatar: '',
        gender: '',
        labels: []
      }));
    } else {
      selectedCustomerServiceFriends.value = [];
    }
  } else {
    // 重置表单
    Object.assign(medicationReminderForm, {
      id: undefined,
      wxId: msgprofilewx_id.value,
      sendWxId: currentUserWxId.value,
      day: undefined,
      triple: undefined,
      productName: '',
      message: '',
      status: '1',
      customerService: '',
      customerServiceStatus: '0',
      deadline: ''
    });

    // 重置间隔天数相关变量
    dayType.value = 'daily';
    customDayValue.value = undefined;

    // 重置客服好友选择
    selectedCustomerServiceFriends.value = [];
  }

  medicationReminderDialogVisible.value = true;
};

// 间隔天数处理方法
const handleDayTypeChange = (value: 'daily' | 'custom') => {
  if (value === 'daily') {
    medicationReminderForm.day = 0;
    customDayValue.value = undefined;
  } else {
    medicationReminderForm.day = customDayValue.value;
  }
};

const handleCustomDayChange = (value: number) => {
  medicationReminderForm.day = value;
};

// 客服好友选择相关方法
const handleRemoveCustomerServiceFriend = (friend: any) => {
  const index = selectedCustomerServiceFriends.value.findIndex((f) => f.wx_id === friend.wx_id);
  if (index > -1) {
    selectedCustomerServiceFriends.value.splice(index, 1);
    medicationReminderForm.customerService = selectedCustomerServiceFriends.value.map((f) => f.wx_id).join(',');

    // 触发表单验证
    if (medicationReminderFormRef.value) {
      medicationReminderFormRef.value.validateField('customerService');
    }
  }
};

const handleCustomerServiceFriendSelectConfirm = (friends: any[]) => {
  // 更新选中的客服好友列表
  selectedCustomerServiceFriends.value = friends;

  // 更新表单中的所属客服字段
  if (friends.length > 0) {
    // 如果是多选，用逗号分隔；如果是单选，直接使用第一个
    medicationReminderForm.customerService = friends.map((f) => f.wx_id).join(',');
  } else {
    medicationReminderForm.customerService = '';
  }

  // 触发表单验证
  if (medicationReminderFormRef.value) {
    medicationReminderFormRef.value.validateField('customerService');
  }

  customerServiceFriendSelectDialogVisible.value = false;
};

// 提交用药提醒表单
const submitMedicationReminderForm = async () => {
  if (!medicationReminderFormRef.value) return;

  await medicationReminderFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        medicationReminderLoading.value = true;

        const formData = {
          ...medicationReminderForm,
          deadline: medicationReminderForm.deadline ? dayjs(medicationReminderForm.deadline).format('YYYY-MM-DD') : undefined
        };

        // 调用 updateMedicationReminder API
        const { updateMedicationReminder } = await import('@/api/userMange/userMangePath');
        const response = await updateMedicationReminder(formData);
        const res = response as any;

        if (res.code === 200) {
          ElMessage.success('保存成功');
          medicationReminderDialogVisible.value = false;
          // 重新加载用药提醒信息
          await loadCustomerMedicationReminder(currentUserWxId.value);
        } else {
          ElMessage.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存用药提醒失败:', error);
        ElMessage.error('保存失败');
      } finally {
        medicationReminderLoading.value = false;
      }
    }
  });
};

// 加载购买记录总数（用于显示摘要）
const loadPurchaseRecordSummary = async (wxId: string) => {
  try {
    const { getPurchaseRecordList } = await import('@/api/userMange/userMangePath');
    const params: any = {
      current: 1,
      size: 3, // 只获取前3条用于外部展示
      wxId: wxId,
      myWxId: msgprofilewx_id.value
    };

    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    const response = await getPurchaseRecordList(params);
    const res = response as any;
    if (res.code === 200) {
      purchaseRecordList.value = res.data?.records || [];
      purchaseRecordTotal.value = res.data?.total || 0;
    }
  } catch (error) {
    console.error('获取购买记录失败:', error);
    purchaseRecordList.value = [];
    purchaseRecordTotal.value = 0;
  }
};

// 加载客户用药提醒信息
const loadCustomerMedicationReminder = async (wxId: string) => {
  try {
    const { getMedicationReminderList } = await import('@/api/userMange/userMangePath');
    const res = await getMedicationReminderList({
      sendWxId: wxId, // 查询时使用客户的微信ID作为接收人ID
      wxId: msgprofilewx_id.value // 当前登录用户的微信ID
    });
    const response = res as any;
    if (response.code === 200 && response.data?.records?.length > 0) {
      customerMedicationReminder.value = response.data.records[0];
    } else {
      customerMedicationReminder.value = null;
    }
  } catch (error) {
    console.error('获取用药提醒失败:', error);
    customerMedicationReminder.value = null;
  }
};

const tagOptions = ref<Tag[]>([]);

// 获取标签列表
const fetchTagOptions = async () => {
  try {
    const res = await getAllLabel();
    tagOptions.value = res.data.map((item: any) => ({
      id: String(item.id),
      label_name: item.label_name
    }));
  } catch (error) {
    console.error('获取标签列表失败:', error);
    ElMessage.error('获取标签列表失败');
  }
};

// 添加标签
const addTag = async () => {
  await fetchTagOptions();
  selectedTags.value = messageContent.value.tags.map((tag) => ({ ...tag, id: String(tag.id) }));
  tagDialogVisible.value = true;
};

// 处理标签选择
const handleTagSelect = (tag: Tag) => {
  const index = selectedTags.value.findIndex((t) => t.id === tag.id);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tag);
  }
};

// 确认添加标签
const confirmAddTag = async () => {
  // if (selectedTags.value.length === 0) {
  //   ElMessage.warning('请至少选择一个新标签');
  //   return;
  // }
  try {
    // 根据是否是群聊来决定使用的参数
    const isGroup = !!messageContent.value.group_id;
    const targetId = isGroup ? messageContent.value.group_id : messageContent.value.wx_id;
    const type = isGroup ? '2' : '0'; // 2表示群聊，0表示好友

    const res = await import('@/api/userRate/label').then((m) =>
      m.updateUserLabel(selectedTags.value.map((tag) => tag.id).join(','), msgprofilewx_id.value, targetId, type)
    );
    if (res && res.code === 200) {
      messageContent.value.tags = [...selectedTags.value];
      ElMessage.success(isGroup ? '群聊标签修改成功' : '标签修改成功');
      selectedTags.value = [];
      tagDialogVisible.value = false;
    } else {
      ElMessage.error(res && res.msg ? res.msg : '标签修改失败');
    }
  } catch (error) {
    console.error('添加标签失败:', error);
    ElMessage.error('添加标签失败');
  }
};

// 处理自定义标签
const handleCustomTag = async () => {
  if (newTag.value.trim()) {
    // 禁止重复添加：已在 messageContent.value.tags 或 selectedTags 里
    const tagExists =
      messageContent.value.tags.some((tag) => tag.label_name === newTag.value) || selectedTags.value.some((tag) => tag.label_name === newTag.value);
    if (tagExists) {
      ElMessage.warning('该标签已存在或已选择');
      return;
    }
    try {
      await addLabel(newTag.value);
      await fetchTagOptions();
      newTag.value = '';
      ElMessage.success('添加自定义标签成功');
    } catch (error) {
      console.error('添加自定义标签失败:', error);
      ElMessage.error('添加自定义标签失败');
    }
  }
};

// 删除标签
const deleteTag = async (tag: Tag) => {
  try {
    // 从当前标签列表中移除要删除的标签
    const newTags = messageContent.value.tags.filter((t) => t.id !== tag.id);
    // 获取剩余标签的 ID 列表
    const remainingTagIds = newTags.map((t) => t.id).join(',');
    // 用 updateUserLabel 更新用户标签
    await updateUserLabel(remainingTagIds, msgprofilewx_id.value, messageContent.value.wx_id, '0');
    // 更新本地数据
    messageContent.value.tags = newTags;
    ElMessage.success('删除标签成功');
  } catch (error) {
    console.error('删除标签失败:', error);
    ElMessage.error('删除标签失败');
  }
};

// 更新用户标签
const updateUserLabel = async (ids: string, myWxId: string, sendWxId: string, type: string) => {
  try {
    await import('@/api/userRate/label').then((m) => m.updateUserLabel(ids, myWxId, sendWxId, type));
    // ElMessage.success('标签更新成功');
  } catch (error) {
    console.error('更新标签失败:', error);
    ElMessage.error('更新标签失败');
  }
};

// 添加群聊标签
const addGroupTag = async () => {
  await fetchTagOptions();
  selectedTags.value = messageContent.value.tags.map((tag) => ({ ...tag, id: String(tag.id) }));
  tagDialogVisible.value = true;
};

// 删除群聊标签
const deleteGroupTag = async (tag: Tag) => {
  try {
    // 从当前标签列表中移除要删除的标签
    const newTags = messageContent.value.tags.filter((t) => t.id !== tag.id);
    // 获取剩余标签的 ID 列表
    const remainingTagIds = newTags.map((t) => t.id).join(',');
    // 用 updateUserLabel 更新群聊标签，type为'2'表示群聊
    await updateUserLabel(remainingTagIds, msgprofilewx_id.value, messageContent.value.group_id, '2');
    // 更新本地数据
    messageContent.value.tags = newTags;
    ElMessage.success('删除群聊标签成功');
  } catch (error) {
    console.error('删除群聊标签失败:', error);
    ElMessage.error('删除群聊标签失败');
  }
};

const isQrcodeError = ref(false);

// 添加退出登录处理函数
const handleLogout = async (item: any) => {
  try {
    await ElMessageBox.confirm('确定要退出该账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await msgLogout({ wxId: item.wx_id, account: currentUsername });
    if (res.data) {
      // 从列表中移除该账号
      const index = personalList.value.findIndex((account: any) => account.wx_id === item.wx_id);
      if (index !== -1) {
        personalList.value.splice(index, 1);
        // 更新总数和在线数
        totalPersonCount.value = personalList.value.length;
        onlinePersonCount.value = personalList.value.filter((item: any) => item.isOnline).length;
      }

      // 清除本地存储的相关数据
      localStorage.removeItem('wxLogin');
      localStorage.removeItem('msgprofile');

      ElMessage.success('退出登录成功');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error);
      ElMessage.error('退出登录失败');
    }
  }
};

// 聊天记录相关变量已移至ChatHistory组件中

// 旧的聊天记录方法已移至ChatHistory组件中

// 旧的聊天记录方法已全部移至ChatHistory组件中

// 处理聊天记录组件的消息发送事件
const handleChatHistoryMsgSendMessages = async (params: any) => {
  try {
    const res = await msgSendMessages(params);
    const responseData = res.data.records || res.data;
    const processedMessages = processMessageList(responseData.reverse());

    if (chatHistoryRef.value) {
      if (params.current === '1') {
        // 首次加载或查询
        chatHistoryRef.value.chatHistoryMessages = processedMessages;
      } else {
        // 加载更多
        const currentScrollHeight = chatHistoryRef.value.chatHistoryScrollRef?.scrollHeight || 0;
        chatHistoryRef.value.chatHistoryMessages = [...processedMessages, ...chatHistoryRef.value.chatHistoryMessages];

        // 保持滚动位置
        nextTick(() => {
          if (chatHistoryRef.value?.chatHistoryScrollRef) {
            const newScrollHeight = chatHistoryRef.value.chatHistoryScrollRef.scrollHeight;
            chatHistoryRef.value.chatHistoryScrollRef.scrollTop = newScrollHeight - currentScrollHeight;
          }
        });
      }

      chatHistoryRef.value.chatHistoryHasMore = responseData.length === parseInt(chatHistoryRef.value.chatHistorySize);

      // 首次加载完成后滚动到底部
      if (params.current === '1') {
        nextTick(() => {
          chatHistoryRef.value?.scrollChatHistoryToBottom();
        });
      }
    }
  } catch (error) {
    console.error('查询聊天记录失败:', error);
    ElMessage.error('查询聊天记录失败');
    if (chatHistoryRef.value) {
      chatHistoryRef.value.chatHistoryLoadError = true;
    }
  } finally {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.chatHistoryLoading = false;
    }
  }
};

// 监听选项卡切换，当切换到聊天记录时加载数据
watch(optionsvalue, (newValue) => {
  if (newValue === '聊天记录') {
    // 延迟加载，确保DOM已渲染
    nextTick(() => {
      chatHistoryRef.value?.loadChatHistory();
    });
  }
});

// 滚动防抖定时器
let scrollTimeout: NodeJS.Timeout | null = null;

// 监听滚动事件
const handleScroll = (e: any) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target;

  // 防抖处理，避免频繁触发
  if (scrollTimeout) {
    clearTimeout(scrollTimeout);
  }

  scrollTimeout = setTimeout(() => {
    // 当滚动到顶部附近时（距离顶部小于50px）触发加载更多
    const threshold = 50;
    if (scrollTop <= threshold && !isLoading.value && hasMore.value) {
      loadMoreMessages();
    }

    // 可选：当滚动到底部时，可以标记消息为已读
    const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10;
    if (isAtBottom) {
      // 这里可以添加标记消息为已读的逻辑
      // markMessagesAsRead();
    }
  }, 100); // 100ms防抖
};

// 加载更多消息
const loadMoreMessages = async () => {
  if (isLoading.value || !hasMore.value) return;

  isLoading.value = true;
  loadError.value = false;
  hasTriedLoadMore.value = true; // 标记已经尝试过加载更多
  const currentPage = parseInt(msgcurrent.value);
  msgcurrent.value = (currentPage + 1).toString();

  try {
    let params = {
      wxId: msgprofilewx_id.value,
      current: msgcurrent.value,
      size: msgsize.value,
      ...(nowExprentTag.value === '群聊' ? { group_id: messageContent.value.group_id } : { sendWxId: messageContent.value.wx_id })
    };

    const res = await msgSendMessages(params);
    // 修复数据结构不一致问题，统一使用 records
    const responseData = res.data.records || res.data;
    const newMessages = processMessageList(responseData.reverse());

    if (newMessages.length === 0) {
      hasMore.value = false;
      ElMessage.info('没有更多消息了');
    } else {
      // 检查是否还有更多数据
      hasMore.value = newMessages.length === parseInt(msgsize.value);

      // 保存当前滚动位置
      const scrollbar = scrollbarRef.value;
      const oldHeight = scrollbar.scrollHeight;
      const oldScrollTop = scrollbar.scrollTop;

      // 禁用自动滚动，避免在添加历史消息时滚动到底部
      shouldAutoScroll.value = false;

      // 将新消息添加到列表前面
      messageBody.value = [...newMessages, ...messageBody.value];

      // 等待 DOM 更新后调整滚动位置，保持用户当前查看的消息位置不变
      await nextTick();
      const newHeight = scrollbar.scrollHeight;
      const heightDiff = newHeight - oldHeight;
      scrollbar.scrollTop = oldScrollTop + heightDiff;

      // 重新启用自动滚动
      shouldAutoScroll.value = true;

      console.log(`加载了 ${newMessages.length} 条历史消息`);
    }
  } catch (error) {
    console.error('加载更多消息失败:', error);
    loadError.value = true;
    // 回滚页码
    msgcurrent.value = (parseInt(msgcurrent.value) - 1).toString();
    // 确保在错误情况下也恢复自动滚动
    shouldAutoScroll.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 重试加载消息
const retryLoadMessages = () => {
  loadError.value = false;
  loadMoreMessages();
};

const handleClickMessage = async (element: any, i: number) => {
  isMessageLoading.value = true;
  scrollToBottom();

  // 切换对话时清空消息输入框和@成员
  senMessageContent.value = '';
  selectedAtMembers.value = [];
  showAtMemberSelector.value = false;
  atSearchKeyword.value = '';

  // 先清除所有项的激活状态
  conversations.value.forEach((section: any) => {
    section.data.forEach((item: any) => {
      item.isShow = false;
    });
  });

  // 设置当前项的激活状态
  conversations.value[i].data.forEach((item: any) => {
    item.isShow = item.id == element.id ? true : false;
  });

  nowExprentTag.value = conversations.value[i].groupName;
  messageContent.value.wx_id = element.user_id;
  messageContent.value.group_id = element.group_id;
  radioChange.value = element.ai_type;

  // 重置聊天记录组件状态
  if (chatHistoryRef.value) {
    chatHistoryRef.value.chatSearchForm.dateTime = '';
    chatHistoryRef.value.chatSearchForm.message_type = undefined;
    chatHistoryRef.value.chatSearchForm.message_content = '';

    chatHistoryRef.value.chatHistoryCurrent = '1';
    chatHistoryRef.value.chatHistorySize = '30';
    chatHistoryRef.value.chatHistoryHasMore = true;
    chatHistoryRef.value.chatHistoryLoading = false;
    chatHistoryRef.value.chatHistoryLoadError = false;
    chatHistoryRef.value.chatHistoryHasTriedLoadMore = false;

    chatHistoryRef.value.chatHistoryMessages = [];
  }

  // 根据是否是群聊设置默认的 optionsvalue
  optionsvalue.value = element.group_id ? '群聊信息' : '客户档案';
  await getMessageContet();
  await getMessgeStation();
  await getUser(element.user_id ? element.user_id : element.group_id);

  // 等待 DOM 渲染后滚动到底部
  await nextTick();
  scrollToBottom();
  isMessageLoading.value = false;
};

const getUser = async (id: string) => {
  try {
    const params = {
      wxId: id,
      sendWxId: msgprofilewx_id.value,
      ...(messageContent.value.group_id ? { myWxId: msgprofilewx_id.value } : {})
    };
    const res = await msgGetUser(params);
    messageContent.value = {
      ...messageContent.value,
      wx_id: id,
      avatar_url: res.data.avatar_url,
      nick_name: res.data.remark || res.data.nick_name, // 优先显示备注，没有备注则显示昵称
      remark: res.data.remark, // 保存备注
      wx_account: res.data.wx_account,
      age: res.data.user_age,
      gender: res.data.user_gender,
      birthday: res.data.user_birthday,
      phone: res.data.user_phone,
      address: res.data.user_address,
      description: res.data.user_description,
      source: res.data.user_customer_source,
      employee: res.data.user_assigned_employee,
      qq: res.data.user_qq,
      email: res.data.user_email,
      tags: res.data.labels.map((label: any) => ({
        id: label.id || label.label_id,
        label_name: label.label_name
      })),
      groupMembers: res.data.groupMembers,
      group_member_count: res.data.group_member_count
    };

    // 如果不是群聊，获取客户动态数据
    if (!messageContent.value.group_id) {
      // 重置分页信息
      activitiesPage.value = {
        current: 1,
        size: 20,
        total: 0,
        hasMore: true
      };
      messageContent.value.activities = [];

      // 加载第一页数据
      await loadCustomerActivities(id, true);

      // 加载购买记录总数
      loadPurchaseRecordSummary(id);

      // 加载用药提醒信息
      loadCustomerMedicationReminder(id);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 刷新客户动态数据
const refreshingActivities = ref(false);
const refreshCountdown = ref(0);
let refreshTimer: NodeJS.Timeout | null = null;

// 客户动态分页相关
const activitiesLoading = ref(false);
const activitiesPage = ref({
  current: 1,
  size: 20,
  total: 0,
  hasMore: true
});

// 添加客户动态相关
const addActivityDialogVisible = ref(false);
const addActivityLoading = ref(false);
const addActivityFormRef = ref();
const addActivityForm = reactive({
  remark: ''
});

// WebSocket连接状态
const connectionStatus = ref<'connecting' | 'connected' | 'disconnected' | 'error'>('disconnected');
const connectionStats = ref({
  reconnectCount: 0,
  shouldKeepAlive: false,
  isReconnecting: false,
  currentUsername: '',
  readyState: WebSocket.CLOSED
});

// 连接状态计算属性
const connectionStatusClass = computed(() => {
  return `status-${connectionStatus.value}`;
});

const connectionStatusText = computed(() => {
  const statusMap = {
    connecting: '连接中',
    connected: '已连接',
    disconnected: '未连接',
    error: '连接错误'
  };
  return statusMap[connectionStatus.value];
});

// 获取连接提示信息
const getConnectionTooltip = () => {
  const stats = connectionStats.value;
  return `连接状态: ${connectionStatusText.value}\n重连次数: ${stats.reconnectCount}\n用户: ${stats.currentUsername}\n保持连接: ${
    stats.shouldKeepAlive ? '是' : '否'
  }`;
};

// 显示连接统计信息
const showConnectionStats = () => {
  const stats = websocket.getConnectionStats();
  connectionStats.value = stats;
  console.log('WebSocket连接统计:', stats);
  ElMessage.info(`连接统计: 重连${stats.reconnectCount}次, 状态${connectionStatusText.value}`);
};

// 测试WebSocket连接
const testWebSocketConnection = () => {
  console.log('=== WebSocket连接测试 ===');
  const stats = websocket.getConnectionStats();
  console.log('连接统计:', stats);
  console.log('连接状态:', websocket.getReadyState());
  console.log('是否连接:', websocket.isConnected());

  if (websocket.isConnected()) {
    console.log('发送测试心跳...');
    websocket.ping();
    ElMessage.success('连接正常，已发送心跳测试');
  } else {
    console.log('连接已断开，尝试重连...');
    websocket.enableKeepAlive();
    websocket.reconnect();
    ElMessage.warning('连接已断开，正在重连...');
  }

  // 更新连接统计
  connectionStats.value = websocket.getConnectionStats();
};

// WebSocket状态监控 - 永久保持连接
const setupWebSocketMonitor = () => {
  let monitorTimer: NodeJS.Timeout;

  const checkWebSocketStatus = () => {
    const readyState = websocket.getReadyState();
    const stats = websocket.getConnectionStats();

    // 更新连接统计信息
    connectionStats.value = stats;

    // 更新连接状态显示（仅用于UI显示，不触发重连）
    if (readyState === WebSocket.OPEN) {
      connectionStatus.value = 'connected';
    } else if (readyState === WebSocket.CONNECTING) {
      connectionStatus.value = 'connecting';
    } else if (readyState === WebSocket.CLOSED) {
      connectionStatus.value = 'disconnected';
      // 移除页面级别的重连逻辑，避免与socket.ts中的重连冲突
    } else {
      connectionStatus.value = 'error';
    }
  };

  // 每60秒检查一次连接状态（降低检查频率，避免冲突）
  monitorTimer = setInterval(checkWebSocketStatus, 60000);

  // 立即执行一次检查
  checkWebSocketStatus();

  // 在组件卸载时清理定时器
  onBeforeUnmount(() => {
    if (monitorTimer) {
      clearInterval(monitorTimer);
    }
  });
};

// 页面可见性监听 - 永久保持连接
const setupVisibilityListener = () => {
  const handleVisibilityChange = () => {
    if (document.hidden) {
    } else {
      // 页面重新显示时强化连接检查
      const stats = websocket.getConnectionStats();
      // 更新统计信息
      connectionStats.value = stats;

      if (!websocket.isConnected()) {
        connectionStatus.value = 'connecting';
        websocket.enableKeepAlive(); // 确保启用永久保持
        websocket.reconnect();
      } else {
        // 发送心跳检测连接强度
        websocket.ping();
        connectionStatus.value = 'connected';
      }
    }
  };

  document.addEventListener('visibilitychange', handleVisibilityChange);

  // 添加窗口焦点监听
  const handleFocus = () => {
    if (!websocket.isConnected() && msgprofilewx_id.value) {
      websocket.enableKeepAlive();
      websocket.reconnect();
    }
  };

  window.addEventListener('focus', handleFocus);

  // 在组件卸载时清理监听器
  onBeforeUnmount(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange);
    window.removeEventListener('focus', handleFocus);
  });
};

// 添加动态表单验证规则
const addActivityRules = {
  remark: [
    { required: true, message: '请输入动态内容', trigger: 'blur' },
    { min: 1, max: 500, message: '动态内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
};

// 加载客户动态数据
const loadCustomerActivities = async (customerWxId: string, isRefresh = false) => {
  if (activitiesLoading.value || (!activitiesPage.value.hasMore && !isRefresh)) {
    return;
  }

  activitiesLoading.value = true;

  try {
    const params = {
      wxId: msgprofilewx_id.value,
      customerWxId: customerWxId,
      current: isRefresh ? 1 : activitiesPage.value.current,
      size: activitiesPage.value.size
    };

    const dynamicRes = await getCustomerLogList(params);

    if (dynamicRes.code === 200 && dynamicRes.data) {
      const { records, total, current, size } = dynamicRes.data;

      // 转换数据格式
      const newActivities = records.map((item: any) => ({
        time: item.date_time,
        type: getActivityType(item.log_type),
        color: getActivityColor(item.log_type),
        title: item.log_type_str,
        description: item.remark
      }));

      if (isRefresh) {
        // 刷新时替换所有数据
        messageContent.value.activities = newActivities;
        activitiesPage.value.current = 1;
      } else {
        // 加载更多时追加数据
        messageContent.value.activities.push(...newActivities);
      }

      // 更新分页信息
      activitiesPage.value.total = total;
      activitiesPage.value.current = current;
      activitiesPage.value.hasMore = records.length === size && current * size < total;
    }
  } catch (error) {
    console.error('加载客户动态失败:', error);
    if (isRefresh) {
      ElMessage.error('加载客户动态失败');
    }
  } finally {
    activitiesLoading.value = false;
  }
};

const refreshCustomerActivities = async () => {
  if (!messageContent.value.wx_id || messageContent.value.group_id) {
    return;
  }

  // 防止重复点击
  if (refreshingActivities.value) {
    return;
  }

  // 检查倒计时
  if (refreshCountdown.value > 0) {
    ElMessage.warning(`请等待 ${refreshCountdown.value} 秒后再刷新`);
    return;
  }

  refreshingActivities.value = true;
  try {
    // 重置分页信息
    activitiesPage.value = {
      current: 1,
      size: 20,
      total: 0,
      hasMore: true
    };

    // 刷新第一页数据
    await loadCustomerActivities(messageContent.value.wx_id, true);

    // 刷新成功后开始倒计时
    startRefreshCountdown();
  } catch (error) {
    console.error('刷新客户动态失败:', error);
    ElMessage.error('刷新客户动态失败');
  } finally {
    refreshingActivities.value = false;
  }
};

// 加载更多客户动态
const loadMoreActivities = async () => {
  if (!messageContent.value.wx_id || messageContent.value.group_id) {
    return;
  }

  // 增加页码
  activitiesPage.value.current += 1;

  // 加载下一页数据
  await loadCustomerActivities(messageContent.value.wx_id, false);
};

// 显示添加动态对话框
const showAddActivityDialog = () => {
  if (!messageContent.value.wx_id || messageContent.value.group_id) {
    ElMessage.warning('请先选择一个好友');
    return;
  }

  // 重置表单
  addActivityForm.remark = '';
  addActivityDialogVisible.value = true;
};

// 提交添加动态
const submitAddActivity = async () => {
  try {
    // 验证表单
    await addActivityFormRef.value?.validate();

    addActivityLoading.value = true;

    // 调用添加动态接口
    const response = await addCustomerLog({
      logType: 1,
      wxId: msgprofilewx_id.value,
      customerWxId: messageContent.value.wx_id,
      remark: addActivityForm.remark
    });

    if (response.code === 200) {
      ElMessage.success('动态添加成功');
      addActivityDialogVisible.value = false;

      // 重置分页并重新加载动态列表（不启动倒计时）
      activitiesPage.value = {
        current: 1,
        size: 20,
        total: 0,
        hasMore: true
      };
      messageContent.value.activities = [];
      await loadCustomerActivities(messageContent.value.wx_id, true);
    } else {
      ElMessage.error(response.msg || '动态添加失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('添加动态失败:', error);
      ElMessage.error('动态添加失败');
    }
  } finally {
    addActivityLoading.value = false;
  }
};

// 开始刷新倒计时
const startRefreshCountdown = () => {
  refreshCountdown.value = 60; // 60秒倒计时

  if (refreshTimer) {
    clearInterval(refreshTimer);
  }

  refreshTimer = setInterval(() => {
    refreshCountdown.value--;
    if (refreshCountdown.value <= 0) {
      clearInterval(refreshTimer!);
      refreshTimer = null;
    }
  }, 1000);
};

const toggleSection = (sectionId: number): void => {
  const sectionIndex = conversations.value.findIndex((s: any, i: number) => i === sectionId);
  if (sectionIndex !== -1) {
    conversations.value[sectionIndex].expanded = !conversations.value[sectionIndex].expanded;
  }
};

// 添加获取待添加好友列表的方法
const getPendingFriends = async (wxId: string) => {
  if (!wxId) {
    ElMessage.warning('请先登录微信');
    return;
  }

  try {
    const res = await seleteWechatFriends({ wxId });

    if (res.code === 200 && res.data) {
      adduserSections.value = [
        {
          id: 1,
          key: '新的朋友',
          value: res.data
        }
      ];
    } else {
      ElMessage.error(res.msg || '获取待添加好友列表失败');
    }
  } catch (error) {
    ElMessage.error('获取待添加好友列表失败');
  }
};

// 添加接受好友请求的方法
const handleAcceptFriend = async (friend: any) => {
  try {
    const res = await friendAdd({ id: friend.id });
    if (res.code === 200) {
      ElMessage.success('已接受好友请求');
      // 不再移除已接受的好友，直接修改状态为已通过
      friend.status = 2;
    } else {
      ElMessage.error(res.msg || '接受好友请求失败');
    }
  } catch (error) {
    ElMessage.error('接受好友请求失败');
  }
};

// 添加时间格式化函数
const formatTime = (time: string) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 今天内
  if (diff < 24 * 60 * 60 * 1000) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  // 一周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[date.getDay()];
  }
  // 更早
  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
};

// 添加好友相关
const showAddFriendDialog = ref(false);
const searchResult = ref<any>(null);
const addFriendForm = ref({
  key: '',
  msg: ''
});

// 预设验证消息相关
const presetMessages = ref<any[]>([]);

// 监听弹窗关闭
watch(showAddFriendDialog, (newVal) => {
  if (!newVal) {
    searchResult.value = null;
    addFriendForm.value = {
      key: '',
      msg: ''
    };
    presetMessages.value = []; // 清空预设消息
  }
});

// 监听微信号输入
watch(
  () => addFriendForm.value.key,
  (newVal) => {
    if (!newVal) {
      searchResult.value = null;
    }
  }
);

const unreadCount = computed(() => {
  let count = 0;
  if (conversations.value) {
    (conversations.value as any[]).forEach((group: any) => {
      if (group.data) {
        (group.data as any[]).forEach((item: any) => {
          if (typeof item.unread === 'number') {
            count += item.unread;
          }
        });
      }
    });
  }
  return count;
});

const showEmojiPicker = ref(false);
const emojiPickerRef = ref<HTMLElement | null>(null);

// @群成员功能相关
const showAtMemberSelector = ref(false);
const atSearchKeyword = ref('');
const selectedAtMembers = ref<Array<{ user_id: string; user_name: string }>>([]);

const zhConfig = {
  search: '搜索',
  categories: {
    recents: '最近使用',
    smileys: '表情',
    people: '人物',
    animals: '动物',
    food: '食物',
    activities: '活动',
    travel: '旅行',
    objects: '物品',
    symbols: '符号',
    flags: '旗帜'
  },
  notFound: '没有找到表情'
};
const toggleEmojiPicker = (event: MouseEvent) => {
  event.stopPropagation();
  // ElMessage.info('表情选择功能正在开发中，敬请期待！');
  showEmojiPicker.value = !showEmojiPicker.value;
};

// @群成员功能相关方法
const filteredGroupMembers = computed(() => {
  if (!messageContent.value.groupMembers) {
    return [];
  }

  // 过滤掉当前用户自己
  let members = messageContent.value.groupMembers.filter((member) => member.user_id !== msgprofilewx_id.value);

  // 如果有搜索关键词，进一步过滤
  if (atSearchKeyword.value) {
    members = members.filter((member) => member.user_name.toLowerCase().includes(atSearchKeyword.value.toLowerCase()));
  }

  return members;
});

// 处理输入框内容变化
const handleInputChange = (value: string) => {
  if (!messageContent.value.group_id) {
    showAtMemberSelector.value = false;
    return;
  }

  // 检查已@的成员是否在输入框中被删除
  const currentAtMembers = [...selectedAtMembers.value];
  for (const member of currentAtMembers) {
    const atText = `@${member.user_name}`;
    if (!value.includes(atText)) {
      // 如果输入框中不再包含这个@用户名，从已@列表中移除
      const index = selectedAtMembers.value.findIndex((m) => m.user_id === member.user_id);
      if (index !== -1) {
        selectedAtMembers.value.splice(index, 1);
        console.log(`已从@列表中移除: ${member.user_name}`);
      }
    }
  }

  // 检查是否输入了@符号
  const atIndex = value.lastIndexOf('@');
  if (atIndex !== -1) {
    // 获取@后面的搜索关键词
    const searchText = value.substring(atIndex + 1);

    // 如果@后面没有空格，显示群成员选择器
    if (!searchText.includes(' ')) {
      atSearchKeyword.value = searchText;
      showAtMemberSelector.value = true;
    } else {
      showAtMemberSelector.value = false;
    }
  } else {
    showAtMemberSelector.value = false;
  }
};

// 选择@的群成员
const selectAtMember = (member: any) => {
  // 检查是否尝试@自己
  if (member.user_id === msgprofilewx_id.value) {
    ElMessage.warning('不能@自己');
    showAtMemberSelector.value = false;
    atSearchKeyword.value = '';
    return;
  }

  // 检查是否已经@过这个成员
  if (selectedAtMembers.value.find((m) => m.user_id === member.user_id)) {
    ElMessage.warning(`已经@过 ${member.user_name} 了`);
    showAtMemberSelector.value = false;
    atSearchKeyword.value = '';
    return;
  }

  const atIndex = senMessageContent.value.lastIndexOf('@');
  if (atIndex !== -1) {
    // 替换@及其后面的内容为@用户名
    const beforeAt = senMessageContent.value.substring(0, atIndex);
    const newContent = beforeAt + `@${member.user_name} `;

    // 检查字数限制
    if (newContent.length > 2000) {
      ElMessage.warning('添加@用户名后内容将超过2000个字符限制');
      showAtMemberSelector.value = false;
      atSearchKeyword.value = '';
      return;
    }

    senMessageContent.value = newContent;

    // 记录被@的成员
    selectedAtMembers.value.push({
      user_id: member.user_id,
      user_name: member.user_name
    });
  }

  showAtMemberSelector.value = false;
  atSearchKeyword.value = '';
};

// 快速@群成员（从群成员列表点击）
const quickAtMember = (member: any) => {
  // 检查是否尝试@自己
  if (member.user_id === msgprofilewx_id.value) {
    ElMessage.warning('不能@自己');
    return;
  }

  // 检查是否已经@过这个成员
  if (selectedAtMembers.value.find((m) => m.user_id === member.user_id)) {
    ElMessage.warning(`已经@过 ${member.user_name} 了`);
    return;
  }

  // 在输入框末尾添加@用户名
  let newContent = senMessageContent.value;
  if (newContent && !newContent.endsWith(' ')) {
    newContent += ' ';
  }
  newContent += `@${member.user_name} `;

  // 检查字数限制
  if (newContent.length > 2000) {
    ElMessage.warning('添加@用户名后内容将超过2000个字符限制');
    return;
  }

  senMessageContent.value = newContent;

  // 记录被@的成员
  selectedAtMembers.value.push({
    user_id: member.user_id,
    user_name: member.user_name
  });

  ElMessage.success(`已@${member.user_name}`);
};

// 移除@的成员
const removeAtMember = (member: any) => {
  const index = selectedAtMembers.value.findIndex((m) => m.user_id === member.user_id);
  if (index !== -1) {
    selectedAtMembers.value.splice(index, 1);

    // 从输入框中移除@用户名
    const atText = `@${member.user_name}`;
    senMessageContent.value = senMessageContent.value.replace(new RegExp(atText + '\\s*', 'g'), '');
  }
};

// 清空输入框和@成员
const clearMessageInput = () => {
  senMessageContent.value = '';
  selectedAtMembers.value = [];
  showAtMemberSelector.value = false;
  atSearchKeyword.value = '';
};

// 文件下载处理函数
const handleDownloadFile = (item: any) => {
  try {
    if (!item.message_content) {
      ElMessage.error('文件路径不存在');
      return;
    }
    const fileUrl = imageUrlfirst + item.message_content;
    let fileName = item.media_file_id || '下载文件';
    if (item.file_last_name && !fileName.includes('.')) {
      fileName += item.file_last_name;
    }
    fileName = fileName.replace(/[<>:"/\\|?*]/g, '_');
    fetch(fileUrl)
      .then((response) => {
        if (!response.ok) {
          throw new Error('网络响应不正常');
        }
        return response.blob();
      })
      .then((blob) => {
        const blobUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = fileName;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
      })
      .catch((error) => {
        console.error('Fetch下载失败，尝试直接下载:', error);
        const link = document.createElement('a');
        link.href = fileUrl;
        link.download = fileName;
        link.target = '_blank';
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
  } catch (error) {
    console.error('文件下载失败:', error);
    ElMessage.error('文件下载失败');
  }
};
// 处理AI推荐消息点击
const handleAiMessageClick = (aiMessage: string) => {
  if (!aiMessage) return;

  // 检查AI推荐消息长度
  if (aiMessage.length > 2000) {
    ElMessage.warning('AI推荐消息内容超过2000个字符，已截取前2000个字符');
    senMessageContent.value = aiMessage.substring(0, 2000);
  } else {
    senMessageContent.value = aiMessage;
  }
};

const onSelectEmoji = (emoji: any) => {
  // 插入到光标处
  const textarea = document.querySelector('.messageContent-bodyinput textarea') as HTMLTextAreaElement;
  if (textarea) {
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = senMessageContent.value;
    const newText = text.substring(0, start) + emoji.i + text.substring(end);

    // 检查字数限制
    if (newText.length > 2000) {
      ElMessage.warning('添加表情后内容将超过2000个字符限制');
      showEmojiPicker.value = false;
      return;
    }

    senMessageContent.value = newText;
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + emoji.i.length;
      textarea.focus();
    });
  } else {
    const newText = senMessageContent.value + emoji.i;

    // 检查字数限制
    if (newText.length > 2000) {
      ElMessage.warning('添加表情后内容将超过2000个字符限制');
      showEmojiPicker.value = false;
      return;
    }

    senMessageContent.value = newText;
  }
  showEmojiPicker.value = false;
};
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (emojiPickerRef.value && !emojiPickerRef.value.contains(target) && !target.closest('.emoji-trigger')) {
    showEmojiPicker.value = false;
  }
};
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

const emojiIconRef = ref<HTMLElement | null>(null);
const emojiPickerStyle = computed(() => {
  if (!emojiIconRef.value) return '';
  const rect = emojiIconRef.value.getBoundingClientRect();
  // 绝对定位到按钮正上方，右对齐
  return `position: fixed; right: ${window.innerWidth - rect.right - 235}px; top: ${rect.top - 335}px; z-index: 1000; `;
});

// 替换原有 showAddFriendDialog 相关 watch、方法
const onAddFriendSuccess = () => {
  // 添加成功后刷新待添加好友列表
  if (personalList.value.length > 0) {
    updateAddFriends();
    getPendingFriends(personalList.value[0].wx_id);
  }
};

const handleTranscribeAudio = async (item: any) => {
  // 如果已经有转文字结果，再次点击则取消显示
  if (item.transcribedText) {
    item.transcribedText = '';
    ElMessage.info('已取消转文字显示');
    return;
  }

  if (!item.id) {
    ElMessage.warning('消息ID不存在');
    return;
  }

  try {
    // 设置转文字状态
    item.transcribing = true;

    // 调用转文字接口
    const res = await speechToText(item.id);

    if (res.msg) {
      // 保存转文字结果
      item.transcribedText = res.msg;
      ElMessage.success('转文字成功');
    } else {
      ElMessage.error('转文字失败');
    }
  } catch (error) {
    console.error('转文字失败:', error);
    ElMessage.error('转文字失败');
  } finally {
    // 清除转文字状态
    item.transcribing = false;
  }
};

const cancelCreateGroup = () => {
  // 恢复创建状态
  isCreatGroup.value = false;

  // 清除所有选中状态
  usersSections.value.forEach((item: any) => {
    item.value.forEach((ele: any) => {
      ele.checked = false;
    });
  });

  ElMessage.info('已取消创建群聊');
};

// 根据日志类型获取活动类型
const getActivityType = (logType: string) => {
  const typeMap: { [key: string]: string } = {
    '1': 'primary', // 跟进记录
    '2': 'success', // 成交记录
    '3': 'warning', // 投诉记录
    '4': 'danger', // 流失记录
    '5': 'info' // 其他记录
  };
  return typeMap[logType] || 'primary';
};

// 根据日志类型获取活动颜色
const getActivityColor = (logType: string) => {
  const colorMap: { [key: string]: string } = {
    '1': '#2b7bef', // 跟进记录 - 蓝色
    '2': '#44cb84', // 成交记录 - 绿色
    '3': '#e6a23c', // 投诉记录 - 橙色
    '4': '#f56c6c', // 流失记录 - 红色
    '5': '#909399' // 其他记录 - 灰色
  };
  return colorMap[logType] || '#2b7bef';
};

const isFileUploading = ref(false);

watch(tagDialogVisible, async (val) => {
  if (val) {
    await fetchTagOptions();
    selectedTags.value = messageContent.value.tags.map((tag) => ({ ...tag, id: String(tag.id) }));
  }
});
</script>

<style scoped lang="scss">
@use './weChat.scss';
</style>
